file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma experimental ABIEncoderV2; pragma solidity 0.7.3; import "./interfaces/IProxy.sol"; import "./interfaces/IPV2SmartPool.sol"; import "./interfaces/IBPool.sol"; import "./interfaces/IBFactory.sol"; import "./interfaces/ISmartPoolStorageDoctor.sol"; import "./interfaces/IExperiPieStorageDoctor.sol"; import "@pie-dao/diamond/contracts/Diamond.sol"; import "@pie-dao/diamond/contracts/interfaces/IDiamondCut.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@pie-dao/pie-vaults/contracts/interfaces/IExperiPie.sol"; import "hardhat/console.sol"; contract Experinator is Ownable { address diamondImplementation; address experiPieStorageDoctor; address balancerFactory; address smartPoolImplementation; address smartPoolStorageDoctor; IDiamondCut.FacetCut[] public diamondCut; constructor( // IDiamondCut.FacetCut[] memory _diamondCut, address _diamondImplementation, address _balancerFactory, address _smartPoolImplementation, address _smartPoolStorageDoctor, address _experiPieStorageDoctor ) { // setCut(_diamondCut); diamondImplementation = _diamondImplementation; balancerFactory = _balancerFactory; smartPoolImplementation = _smartPoolImplementation; smartPoolStorageDoctor = _smartPoolStorageDoctor; experiPieStorageDoctor = _experiPieStorageDoctor; } function setCut(IDiamondCut.FacetCut[] memory _diamondCut) public onlyOwner { delete diamondCut; for(uint256 i = 0; i < _diamondCut.length; i ++) { diamondCut.push(_diamondCut[i]); } } // Make sure its initialised! function setDiamondImplementation(address _diamondImplementation) external onlyOwner { diamondImplementation = _diamondImplementation; } function setBalancerFactory(address _factory) external onlyOwner { balancerFactory = _factory; } function setSmartPoolImplementation(address _smartPoolImplementation) external onlyOwner { smartPoolImplementation = _smartPoolImplementation; } function setSmartPoolStorageDoctor(address _storageDoctor) external onlyOwner { smartPoolStorageDoctor = _storageDoctor; } function setExperiPieStorageDoctor(address _storageDoctor) external onlyOwner { experiPieStorageDoctor = _storageDoctor; } function toExperiPie(address _smartPool, address _controller) external onlyOwner { IProxy proxy = IProxy(_smartPool); Diamond diamond = Diamond(payable(_smartPool)); IPV2SmartPool smartPool = IPV2SmartPool(_smartPool); IExperiPie experiPie = IExperiPie(_smartPool); IBPool bPool = IBPool(smartPool.getBPool()); IExperiPieStorageDoctor eStorage = IExperiPieStorageDoctor(_smartPool); address[] memory tokens = smartPool.getTokens(); console.log("Controller"); console.log(smartPool.getController()); smartPool.setTokenBinder(address(this)); for(uint256 i = 0; i < tokens.length; i ++) { smartPool.unbind(tokens[i]); } smartPool.setTokenBinder(_controller); smartPool.setController(_controller); proxy.setImplementation(experiPieStorageDoctor); eStorage.operate(); proxy.setImplementation(diamondImplementation); diamond.initialize(diamondCut, address(this)); for(uint256 i = 0; i < tokens.length; i++) { IERC20 token = IERC20(tokens[i]); token.transfer(_smartPool, token.balanceOf(address(this))); experiPie.addToken(tokens[i]); } // set proxy contract ownership to the controller experiPie.transferOwnership(_controller); proxy.setProxyOwner(_controller); } function toSmartPool(address _experiPie, address _owner, uint256[] memory _weights) external onlyOwner { IProxy proxy = IProxy(_experiPie); Diamond diamond = Diamond(payable(_experiPie)); IPV2SmartPool smartPool = IPV2SmartPool(_experiPie); IExperiPie experiPie = IExperiPie(_experiPie); ISmartPoolStorageDoctor spStorage = ISmartPoolStorageDoctor(_experiPie); address[] memory tokens = experiPie.getTokens(); require(_weights.length == tokens.length, "ARRAY_LENGTH_MISMATCH"); // deploy a fresh _bPool IBPool bPool = IBPool(IBFactory(balancerFactory).newBPool()); //remove remove tokens and deposit them into a fresh balancer pool for(uint256 i = 0; i < tokens.length; i ++) { experiPie.removeToken(tokens[i]); IERC20 token = IERC20(tokens[i]); uint256 balance = token.balanceOf(_experiPie); experiPie.singleCall(tokens[i], abi.encodeWithSelector(token.transfer.selector, address(this), balance), 0); token.approve(address(bPool), balance); bPool.bind(tokens[i], balance, _weights[i]); } bPool.setController(_experiPie); // set storage doctor as implementation proxy.setImplementation(smartPoolStorageDoctor); spStorage.operate(address(bPool)); proxy.setImplementation(smartPoolImplementation); console.log("pool controller"); console.log(smartPool.getController()); smartPool.setController(_owner); proxy.setProxyOwner(_owner); } // In case migration does not work we handle control back to another address again function setProxyOwner(address _proxy, address _owner) external onlyOwner { IProxy proxy = IProxy(_proxy); proxy.setProxyOwner(_owner); } // In case migration does not work set the smart pool address to another address again function setController(address _pie, address _controller) external onlyOwner { IPV2SmartPool pie = IPV2SmartPool(_pie); pie.setController(_controller); } function setOwner(address _pie, address _owner) external onlyOwner { IExperiPie experiPie = IExperiPie(_pie); experiPie.transferOwnership(_owner); } }
In case migration does not work we handle control back to another address again
function setProxyOwner(address _proxy, address _owner) external onlyOwner { IProxy proxy = IProxy(_proxy); proxy.setProxyOwner(_owner); }
1,802,326
./full_match/4/0xC9434231534B8fab79d9226e1b443c372A966F65/sources/contracts/curation/Curation.sol
Calculate amount of signal that can be bought with tokens in a curation pool. _subgraphDeploymentID Subgraph deployment to mint signal _tokensIn Amount of tokens used to mint signal return Amount of signal that can be bought with tokens/ Get curation pool tokens and signal Init curation pool
function _tokensToSignal(bytes32 _subgraphDeploymentID, uint256 _tokensIn) private view returns (uint256) { CurationPool memory curationPool = pools[_subgraphDeploymentID]; if (curationPool.tokens == 0) { require( _tokensIn >= minimumCurationDeposit, "Curation deposit is below minimum required" ); return BancorFormula(bondingCurve) .calculatePurchaseReturn( SIGNAL_PER_MINIMUM_DEPOSIT, minimumCurationDeposit, defaultReserveRatio, _tokensIn.sub(minimumCurationDeposit) ) .add(SIGNAL_PER_MINIMUM_DEPOSIT); } return BancorFormula(bondingCurve).calculatePurchaseReturn( getCurationPoolSignal(_subgraphDeploymentID), curationPool.tokens, curationPool.reserveRatio, _tokensIn ); }
649,232
/************************************************* * * * AirDrop Dapp * * Developed by Phenom.Team "www.phenom.team" * * * *************************************************/ pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring '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; } } /** * @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. */ constructor() public { owner = tx.origin; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } } /** * @title ERC20 * @dev Standard of ERC20. */ contract ERC20 is Ownable { using SafeMath for uint256; uint public totalSupply; string public name; string public symbol; uint8 public decimals; bool public transferable; mapping(address => uint) balances; mapping(address => mapping (address => uint)) allowed; /** * @dev Get balance of tokens holder * @param _holder holder's address * @return balance of investor */ function balanceOf(address _holder) public view returns (uint) { return balances[_holder]; } /** * @dev Send coins * throws on any error rather then return a false flag to minimize * user errors * @param _to target address * @param _amount transfer amount * * @return true if the transfer was successful */ function transfer(address _to, uint _amount) public returns (bool) { require(_to != address(0) && _to != address(this)); if (!transferable) { require(msg.sender == owner); } balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } /** * @dev An account/contract attempts to get the coins * throws on any error rather then return a false flag to minimize user errors * * @param _from source address * @param _to target address * @param _amount transfer amount * * @return true if the transfer was successful */ function transferFrom(address _from, address _to, uint _amount) public returns (bool) { require(_to != address(0) && _to != address(this)); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); return true; } /** * @dev Allows another account/contract to spend some tokens on its behalf * throws on any error rather then return a false flag to minimize user errors * * also, to minimize the risk of the approve/transferFrom attack vector * approve has to be called twice in 2 separate transactions - once to * change the allowance to 0 and secondly to change it to the new allowance * value * * @param _spender approved address * @param _amount allowance amount * * @return true if the approval was successful */ function approve(address _spender, uint _amount) public returns (bool) { require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * * @param _owner the address which owns the funds * @param _spender the address which will spend the funds * * @return the amount of tokens still avaible for the spender */ function allowance(address _owner, address _spender) public view returns (uint) { return allowed[_owner][_spender]; } /** * @dev Function make token transferable. * * @return the status of issue */ function unfreeze() public onlyOwner { transferable = true; emit Unfreezed(now); } event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); event Unfreezed(uint indexed _timestamp); } /** * @title StandardToken * @dev Token without the ability to release new ones. */ contract StandardToken is ERC20 { using SafeMath for uint256; /** * @dev The Standard token constructor determines the total supply of tokens. */ constructor(string _name, string _symbol, uint8 _decimals, uint _totalSupply, bool _transferable) public { name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; balances[tx.origin] = _totalSupply; transferable = _transferable; emit Transfer(address(0), tx.origin, _totalSupply); } /** * @dev Sends the tokens to a list of addresses. */ function airdrop(address[] _addresses, uint256[] _values) public onlyOwner returns (bool) { require(_addresses.length == _values.length); for (uint256 i = 0; i < _addresses.length; i++) { require(transfer(_addresses[i], _values[i])); } return true; } } /** * @title MintableToken * @dev Token with the ability to release new ones. */ contract MintableToken is Ownable, ERC20 { using SafeMath for uint256; bool public mintingFinished = false; /** * @dev The Standard token constructor determines the total supply of tokens. */ constructor(string _name, string _symbol, uint8 _decimals, bool _transferable) public { name = _name; symbol = _symbol; decimals = _decimals; transferable = _transferable; } modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _holder beneficiary address the tokens will be issued to * @param _value number of tokens to issue */ function mintTokens(address _holder, uint _value) public canMint onlyOwner returns (bool) { require(_value > 0); require(_holder != address(0)); balances[_holder] = balances[_holder].add(_value); totalSupply = totalSupply.add(_value); emit Transfer(address(0), _holder, _value); return true; } /** * @dev Sends the tokens to a list of addresses. */ function airdrop(address[] _addresses, uint256[] _values) public onlyOwner returns (bool) { require(_addresses.length == _values.length); for (uint256 i = 0; i < _addresses.length; i++) { require(mintTokens(_addresses[i], _values[i])); } return true; } /** * @dev Function finishes minting tokens. * * @return the status of issue */ function finishMinting() public onlyOwner { mintingFinished = true; emit MintFinished(now); } event MintFinished(uint indexed _timestamp); } /** * @title TokenCreator * @dev Create new token ERC20. */ contract TokenCreator { using SafeMath for uint256; mapping(address => address[]) public mintableTokens; mapping(address => address[]) public standardTokens; mapping(address => uint256) public amountMintTokens; mapping(address => uint256) public amountStandTokens; /** * @dev Function create standard token. * * @return the address of new token. */ function createStandardToken(string _name, string _symbol, uint8 _decimals, uint _totalSupply, bool _transferable) public returns (address) { address token = new StandardToken(_name, _symbol, _decimals, _totalSupply, _transferable); standardTokens[msg.sender].push(token); amountStandTokens[msg.sender]++; emit TokenCreated(msg.sender, token); return token; } /** * @dev Function create mintable token. * * @return the address of new token. */ function createMintableToken(string _name, string _symbol, uint8 _decimals, bool _transferable) public returns (address) { address token = new MintableToken(_name, _symbol, _decimals, _transferable); mintableTokens[msg.sender].push(token); amountMintTokens[msg.sender]++; emit TokenCreated(msg.sender, token); return token; } event TokenCreated(address indexed _creator, address indexed _token); }
Get balance of tokens holder _holder holder's address return balance of investor/
function balanceOf(address _holder) public view returns (uint) { return balances[_holder]; }
12,956,836
./partial_match/1/0x14A933E66db326db730a0189451b48951353A658/sources/HamacaToken.sol
Sets `amount` as the allowance of `spender` over the caller's tokens. Emits a {Approval} event. @solidity memory-safe-assembly Compute the allowance slot and store the amount. Emit the {Approval} event.
function approve(address spender, uint256 amount) public virtual returns (bool) { assembly { mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, caller()) sstore(keccak256(0x0c, 0x34), amount) mstore(0x00, amount) log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c))) } return true; }
2,665,008
./full_match/73799/0x0b87CdF95cFB8AD5836aF2b61932b4581ad40B2E/sources/contracts/dependencies/MetaToken.sol
tokenSupply - Returns the total supply of a meta token id - ID of the meta token return uint256 - The total supply of the meta token/
function tokenSupply(uint256 id) external view returns (uint256) { return _totalSupply(id); }
16,362,520
// SPDX-License-Identifier: MIT pragma solidity 0.8; // when & why owner would be payable // 5 minute in solidity series contract EasyDonation { // declare an address address payable owner; // init that address constructor() { owner = payable(msg.sender); } // pay to that address // value in wei (1e-18 eth) function buyMeACafee() external payable { (bool success, ) = owner.call{value: msg.value}(""); require(success); } }
pay to that address value in wei (1e-18 eth)
function buyMeACafee() external payable { require(success); }
2,543,100
/** *Submitted for verification at Etherscan.io on 2022-04-08 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; // // OpenZeppelin Contracts v4.4.1 (utils/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 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 (access/Ownable.sol) /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) /** * @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; } } // // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library 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; } } } // // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) /** * @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 (utils/introspection/IERC165.sol) /** * @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 (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) /** * @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; } } // //Interface abstract contract ERC20Interface { function transferFrom(address from, address to, uint256 tokenId) public virtual; function transfer(address recipient, uint256 amount) public virtual; } abstract contract ERC721Interface { function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual; function balanceOf(address owner) public virtual view returns (uint256 balance) ; } abstract contract ERC1155Interface { function safeBatchTransferFrom(address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public virtual; } abstract contract customInterface { function bridgeSafeTransferFrom(address dapp, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public virtual; } contract BatchSwap is Ownable, Pausable, ReentrancyGuard, IERC721Receiver, IERC1155Receiver { address constant ERC20 = 0x90b7cf88476cc99D295429d4C1Bb1ff52448abeE; address constant ERC721 = 0x58874d2951524F7f851bbBE240f0C3cF0b992d79; address constant ERC1155 = 0xEDfdd7266667D48f3C9aB10194C3d325813d8c39; address public TRADESQUAD = 0xdbD4264248e2f814838702E0CB3015AC3a7157a1; address payable public VAULT = payable(0x48c45a687173ec396353cD1E507B26Fa4F6Ff6D9); mapping (address => address) dappRelations; mapping (address => bool) whiteList; using Counters for Counters.Counter; using SafeMath for uint256; uint256 constant secs = 86400; Counters.Counter private _swapIds; // Flag for the createSwap bool private swapFlag; // Swap Struct struct swapStruct { address dapp; address typeStd; uint256[] tokenId; uint256[] blc; bytes data; } // Swap Status enum swapStatus { Opened, Closed, Cancelled } // SwapIntent Struct struct swapIntent { uint256 id; address payable addressOne; uint256 valueOne; address payable addressTwo; uint256 valueTwo; uint256 swapStart; uint256 swapEnd; uint256 swapFee; swapStatus status; } // NFT Mapping mapping(uint256 => swapStruct[]) nftsOne; mapping(uint256 => swapStruct[]) nftsTwo; // Struct Payment struct paymentStruct { bool status; uint256 value; } // Mapping key/value for get the swap infos mapping (address => swapIntent[]) swapList; mapping (uint256 => uint256) swapMatch; // Struct for the payment rules paymentStruct payment; // Checks mapping(uint256 => address) checksCreator; mapping(uint256 => address) checksCounterparty; // Events event swapEvent(address indexed _creator, uint256 indexed time, swapStatus indexed _status, uint256 _swapId, address _swapCounterPart); event paymentReceived(address indexed _payer, uint256 _value); receive() external payable { emit paymentReceived(msg.sender, msg.value); } // Create Swap function createSwapIntent(swapIntent memory _swapIntent, swapStruct[] memory _nftsOne, swapStruct[] memory _nftsTwo) payable public whenNotPaused nonReentrant { if(payment.status) { if(ERC721Interface(TRADESQUAD).balanceOf(msg.sender)==0) { require(msg.value>=payment.value.add(_swapIntent.valueOne), "Not enought WEI for handle the transaction"); _swapIntent.swapFee = getWeiPayValueAmount() ; } else { require(msg.value>=_swapIntent.valueOne, "Not enought WEI for handle the transaction"); _swapIntent.swapFee = 0 ; } } else require(msg.value>=_swapIntent.valueOne, "Not enought WEI for handle the transaction"); _swapIntent.addressOne = payable(msg.sender); _swapIntent.id = _swapIds.current(); checksCreator[_swapIntent.id] = _swapIntent.addressOne ; checksCounterparty[_swapIntent.id] = _swapIntent.addressTwo ; _swapIntent.swapStart = block.timestamp; _swapIntent.swapEnd = 0; _swapIntent.status = swapStatus.Opened ; swapMatch[_swapIds.current()] = swapList[msg.sender].length; swapList[msg.sender].push(_swapIntent); uint256 i; for(i=0; i<_nftsOne.length; i++) nftsOne[_swapIntent.id].push(_nftsOne[i]); for(i=0; i<_nftsTwo.length; i++) nftsTwo[_swapIntent.id].push(_nftsTwo[i]); for(i=0; i<nftsOne[_swapIntent.id].length; i++) { require(whiteList[nftsOne[_swapIntent.id][i].dapp], "A DAPP is not handled by the system"); if(nftsOne[_swapIntent.id][i].typeStd == ERC20) { ERC20Interface(nftsOne[_swapIntent.id][i].dapp).transferFrom(_swapIntent.addressOne, address(this), nftsOne[_swapIntent.id][i].blc[0]); } else if(nftsOne[_swapIntent.id][i].typeStd == ERC721) { ERC721Interface(nftsOne[_swapIntent.id][i].dapp).safeTransferFrom(_swapIntent.addressOne, address(this), nftsOne[_swapIntent.id][i].tokenId[0], nftsOne[_swapIntent.id][i].data); } else if(nftsOne[_swapIntent.id][i].typeStd == ERC1155) { ERC1155Interface(nftsOne[_swapIntent.id][i].dapp).safeBatchTransferFrom(_swapIntent.addressOne, address(this), nftsOne[_swapIntent.id][i].tokenId, nftsOne[_swapIntent.id][i].blc, nftsOne[_swapIntent.id][i].data); } else { customInterface(dappRelations[nftsOne[_swapIntent.id][i].dapp]).bridgeSafeTransferFrom(nftsOne[_swapIntent.id][i].dapp, _swapIntent.addressOne, dappRelations[nftsOne[_swapIntent.id][i].dapp], nftsOne[_swapIntent.id][i].tokenId, nftsOne[_swapIntent.id][i].blc, nftsOne[_swapIntent.id][i].data); } } emit swapEvent(msg.sender, (block.timestamp-(block.timestamp%secs)), _swapIntent.status, _swapIntent.id, _swapIntent.addressTwo); _swapIds.increment(); } // Close the swap function closeSwapIntent(address _swapCreator, uint256 _swapId) payable public whenNotPaused nonReentrant { require(checksCounterparty[_swapId] == msg.sender, "You're not the interested counterpart"); require(swapList[_swapCreator][swapMatch[_swapId]].status == swapStatus.Opened, "Swap Status is not opened"); require(swapList[_swapCreator][swapMatch[_swapId]].addressTwo == msg.sender, "You're not the interested counterpart"); if(payment.status) { if(ERC721Interface(TRADESQUAD).balanceOf(msg.sender)==0) { require(msg.value>=payment.value.add(swapList[_swapCreator][swapMatch[_swapId]].valueTwo), "Not enought WEI for handle the transaction"); // Move the fees to the vault if(payment.value.add(swapList[_swapCreator][swapMatch[_swapId]].swapFee) > 0) VAULT.transfer(payment.value.add(swapList[_swapCreator][swapMatch[_swapId]].swapFee)); } else { require(msg.value>=swapList[_swapCreator][swapMatch[_swapId]].valueTwo, "Not enought WEI for handle the transaction"); if(swapList[_swapCreator][swapMatch[_swapId]].swapFee>0) VAULT.transfer(swapList[_swapCreator][swapMatch[_swapId]].swapFee); } } else require(msg.value>=swapList[_swapCreator][swapMatch[_swapId]].valueTwo, "Not enought WEI for handle the transaction"); swapList[_swapCreator][swapMatch[_swapId]].addressTwo = payable(msg.sender); swapList[_swapCreator][swapMatch[_swapId]].swapEnd = block.timestamp; swapList[_swapCreator][swapMatch[_swapId]].status = swapStatus.Closed; //From Owner 1 to Owner 2 uint256 i; for(i=0; i<nftsOne[_swapId].length; i++) { require(whiteList[nftsOne[_swapId][i].dapp], "A DAPP is not handled by the system"); if(nftsOne[_swapId][i].typeStd == ERC20) { ERC20Interface(nftsOne[_swapId][i].dapp).transfer(swapList[_swapCreator][swapMatch[_swapId]].addressTwo, nftsOne[_swapId][i].blc[0]); } else if(nftsOne[_swapId][i].typeStd == ERC721) { ERC721Interface(nftsOne[_swapId][i].dapp).safeTransferFrom(address(this), swapList[_swapCreator][swapMatch[_swapId]].addressTwo, nftsOne[_swapId][i].tokenId[0], nftsOne[_swapId][i].data); } else if(nftsOne[_swapId][i].typeStd == ERC1155) { ERC1155Interface(nftsOne[_swapId][i].dapp).safeBatchTransferFrom(address(this), swapList[_swapCreator][swapMatch[_swapId]].addressTwo, nftsOne[_swapId][i].tokenId, nftsOne[_swapId][i].blc, nftsOne[_swapId][i].data); } else { customInterface(dappRelations[nftsOne[_swapId][i].dapp]).bridgeSafeTransferFrom(nftsOne[_swapId][i].dapp, dappRelations[nftsOne[_swapId][i].dapp], swapList[_swapCreator][swapMatch[_swapId]].addressTwo, nftsOne[_swapId][i].tokenId, nftsOne[_swapId][i].blc, nftsOne[_swapId][i].data); } } if(swapList[_swapCreator][swapMatch[_swapId]].valueOne > 0) swapList[_swapCreator][swapMatch[_swapId]].addressTwo.transfer(swapList[_swapCreator][swapMatch[_swapId]].valueOne); //From Owner 2 to Owner 1 for(i=0; i<nftsTwo[_swapId].length; i++) { require(whiteList[nftsTwo[_swapId][i].dapp], "A DAPP is not handled by the system"); if(nftsTwo[_swapId][i].typeStd == ERC20) { ERC20Interface(nftsTwo[_swapId][i].dapp).transferFrom(swapList[_swapCreator][swapMatch[_swapId]].addressTwo, swapList[_swapCreator][swapMatch[_swapId]].addressOne, nftsTwo[_swapId][i].blc[0]); } else if(nftsTwo[_swapId][i].typeStd == ERC721) { ERC721Interface(nftsTwo[_swapId][i].dapp).safeTransferFrom(swapList[_swapCreator][swapMatch[_swapId]].addressTwo, swapList[_swapCreator][swapMatch[_swapId]].addressOne, nftsTwo[_swapId][i].tokenId[0], nftsTwo[_swapId][i].data); } else if(nftsTwo[_swapId][i].typeStd == ERC1155) { ERC1155Interface(nftsTwo[_swapId][i].dapp).safeBatchTransferFrom(swapList[_swapCreator][swapMatch[_swapId]].addressTwo, swapList[_swapCreator][swapMatch[_swapId]].addressOne, nftsTwo[_swapId][i].tokenId, nftsTwo[_swapId][i].blc, nftsTwo[_swapId][i].data); } else { customInterface(dappRelations[nftsTwo[_swapId][i].dapp]).bridgeSafeTransferFrom(nftsTwo[_swapId][i].dapp, swapList[_swapCreator][swapMatch[_swapId]].addressTwo, swapList[_swapCreator][swapMatch[_swapId]].addressOne, nftsTwo[_swapId][i].tokenId, nftsTwo[_swapId][i].blc, nftsTwo[_swapId][i].data); } } if(swapList[_swapCreator][swapMatch[_swapId]].valueTwo>0) swapList[_swapCreator][swapMatch[_swapId]].addressOne.transfer(swapList[_swapCreator][swapMatch[_swapId]].valueTwo); emit swapEvent(msg.sender, (block.timestamp-(block.timestamp%secs)), swapStatus.Closed, _swapId, _swapCreator); } // Cancel Swap function cancelSwapIntent(uint256 _swapId) public nonReentrant { require(checksCreator[_swapId] == msg.sender, "You're not the interested counterpart"); require(swapList[msg.sender][swapMatch[_swapId]].addressOne == msg.sender, "You're not the interested counterpart"); require(swapList[msg.sender][swapMatch[_swapId]].status == swapStatus.Opened, "Swap Status is not opened"); //Rollback if(swapList[msg.sender][swapMatch[_swapId]].swapFee>0) payable(msg.sender).transfer(swapList[msg.sender][swapMatch[_swapId]].swapFee); uint256 i; for(i=0; i<nftsOne[_swapId].length; i++) { if(nftsOne[_swapId][i].typeStd == ERC20) { ERC20Interface(nftsOne[_swapId][i].dapp).transfer(swapList[msg.sender][swapMatch[_swapId]].addressOne, nftsOne[_swapId][i].blc[0]); } else if(nftsOne[_swapId][i].typeStd == ERC721) { ERC721Interface(nftsOne[_swapId][i].dapp).safeTransferFrom(address(this), swapList[msg.sender][swapMatch[_swapId]].addressOne, nftsOne[_swapId][i].tokenId[0], nftsOne[_swapId][i].data); } else if(nftsOne[_swapId][i].typeStd == ERC1155) { ERC1155Interface(nftsOne[_swapId][i].dapp).safeBatchTransferFrom(address(this), swapList[msg.sender][swapMatch[_swapId]].addressOne, nftsOne[_swapId][i].tokenId, nftsOne[_swapId][i].blc, nftsOne[_swapId][i].data); } else { customInterface(dappRelations[nftsOne[_swapId][i].dapp]).bridgeSafeTransferFrom(nftsOne[_swapId][i].dapp, dappRelations[nftsOne[_swapId][i].dapp], swapList[msg.sender][swapMatch[_swapId]].addressOne, nftsOne[_swapId][i].tokenId, nftsOne[_swapId][i].blc, nftsOne[_swapId][i].data); } } if(swapList[msg.sender][swapMatch[_swapId]].valueOne > 0) swapList[msg.sender][swapMatch[_swapId]].addressOne.transfer(swapList[msg.sender][swapMatch[_swapId]].valueOne); swapList[msg.sender][swapMatch[_swapId]].swapEnd = block.timestamp; swapList[msg.sender][swapMatch[_swapId]].status = swapStatus.Cancelled; emit swapEvent(msg.sender, (block.timestamp-(block.timestamp%secs)), swapStatus.Cancelled, _swapId, address(0)); } // Set Trade Squad address function setTradeSquadAddress(address _tradeSquad) public onlyOwner { TRADESQUAD = _tradeSquad ; } // Set Vault address function setVaultAddress(address payable _vault) public onlyOwner { VAULT = _vault ; } // Handle dapp relations for the bridges function setDappRelation(address _dapp, address _customInterface) public onlyOwner { dappRelations[_dapp] = _customInterface; } // Handle the whitelist function setWhitelist(address[] memory _dapp, bool _status) public onlyOwner { uint256 i; for(i=0; i< _dapp.length; i++) { whiteList[_dapp[i]] = _status; } } // Edit CounterPart Address function editCounterPart(uint256 _swapId, address payable _counterPart) public { require(checksCreator[_swapId] == msg.sender, "You're not the interested counterpart"); require(msg.sender == swapList[msg.sender][swapMatch[_swapId]].addressOne, "Message sender must be the swap creator"); checksCounterparty[_swapId] = _counterPart; swapList[msg.sender][swapMatch[_swapId]].addressTwo = _counterPart; } // Set the payment function setPayment(bool _status, uint256 _value) public onlyOwner whenNotPaused { payment.status = _status; payment.value = _value * (1 wei); } // Pause / Unpause the contract function pauseContract(bool _paused) public onlyOwner { _paused?_pause():_unpause(); } // Get whitelist status of an address function getWhiteList(address _address) public view returns(bool) { return whiteList[_address]; } // Get Trade fees function getWeiPayValueAmount() public view returns(uint256) { return payment.value; } // Get swap infos function getSwapIntentByAddress(address _creator, uint256 _swapId) public view returns(swapIntent memory) { return swapList[_creator][swapMatch[_swapId]]; } // Get swapStructLength function getSwapStructSize(uint256 _swapId, bool _nfts) public view returns(uint256) { if(_nfts) return nftsOne[_swapId].length ; else return nftsTwo[_swapId].length ; } // Get swapStruct function getSwapStruct(uint256 _swapId, bool _nfts, uint256 _index) public view returns(swapStruct memory) { if(_nfts) return nftsOne[_swapId][_index] ; else return nftsTwo[_swapId][_index] ; } //Interface IERC721/IERC1155 function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external override returns (bytes4) { return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } function onERC1155Received(address operator, address from, uint256 id, uint256 value, bytes calldata data) external override returns (bytes4) { return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); } function onERC1155BatchReceived(address operator, address from, uint256[] calldata id, uint256[] calldata value, bytes calldata data) external override returns (bytes4) { return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")); } function supportsInterface(bytes4 interfaceID) public view virtual override returns (bool) { return interfaceID == 0x01ffc9a7 || interfaceID == 0x4e2312e0; } }
Get swapStructLength
function getSwapStructSize(uint256 _swapId, bool _nfts) public view returns(uint256) { if(_nfts) return nftsOne[_swapId].length ; else return nftsTwo[_swapId].length ; }
7,970,306
pragma solidity 0.4.19; import "zeppelin-solidity/contracts/token/ERC20/PausableToken.sol"; import "./STRTokenProxyStorage.sol"; /** * @title Stream Token */ contract STRToken is STRTokenProxyStorage, PausableToken { function STRToken() public { createTotalSupply(); } /** * @notice ERC-20 tokens descriptions must be constant functions. Normally * they are defined with constant public state variables. We need to * initialize them in the proxy, and assigning to a constant variable is, of * course, forbidden. We define these functions which are ABI compatible and * avoid those issues. */ function symbol() public pure returns (string) { return "STR"; } function name() public pure returns (string) { return "Stream Token"; } function decimals() public pure returns (uint8) { return 18; } /** * Creates the total supply and assigns it to the owner. */ function createTotalSupply() internal { // This should only be callable once require(totalSupply_ == 0); // STR and ETH have the same precision uint256 desiredSupply = 10000000000 ether; totalSupply_ = totalSupply_.add(desiredSupply); balances[owner] = balances[owner].add(desiredSupply); Transfer(0x0, owner, desiredSupply); } /** * @dev This function is used to initialize/update the storage in the proxy * after setting a new implementation. * * @notice This function needs to be public, but it shouldn't be directly * callable from an implementation. It only makes sense in the context of a * proxy. * * @notice This function must check that the storage is in the correct * version using STRTokenProxyStorage#storageVersion and update it. * * @param data Any data needed for the migration. Limited to 32 bytes * because of solidity's delegatecall limitations. Note that if more data * is needed it can be uploaded to a contract, and use this param for its * address. */ function migrateStorage(bytes32 data) public; }
Creates the total supply and assigns it to the owner./ This should only be callable once STR and ETH have the same precision
function createTotalSupply() internal { require(totalSupply_ == 0); uint256 desiredSupply = 10000000000 ether; totalSupply_ = totalSupply_.add(desiredSupply); balances[owner] = balances[owner].add(desiredSupply); Transfer(0x0, owner, desiredSupply); }
6,355,067
// THIS CONTRACT IS UNSAFE because I added two major bugs to make it more // exciting to audit ;) // One bug is easy to spot, and the other is more subtle. The more subtle bug // may or may not be dangerous. But the other is definitely bad. Hint: don't // even trust the comments ;) pragma solidity 0.4.18; import "zeppelin-solidity/contracts/math/SafeMath.sol"; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; contract BuggyContract is Ownable { //// Data types: struct Gift { bool exists; // 0 Only true if this exists uint giftId; // 1 The gift ID address giver; // 2 The address of the giver address recipient; // 3 The address of the recipient uint expiry; // 4 The expiry datetime of the timelock as a // Unix timestamp uint amount; // 5 The amount of ETH bool redeemed; // 6 Whether the funds have already been redeemed bool returned; // 7 Whether the funds were returned to the giver bool refunded; // 8 Whether the funds were refunded to the giver } //// Mappings and state variables: // Total fees collected uint public feesCollected; // Each gift has a unique ID. If you increment this value, you should get // an unused gift ID. uint public nextGiftId; // Whether refunds are allowed. Set this to true using allowRefunds() only // in an emergency. If refundsAllowed is true, claimRefund() will allow a // refund to go through. bool private refundsAllowed; // recipientToGiftIds maps each recipient address to a list of giftIDs of // Gifts they have received. mapping (address => uint[]) public recipientToGiftIds; // giftIdToGift maps each gift ID to its associated gift. mapping (uint => Gift) public giftIdToGift; //// Events: event Constructed (address indexed by, uint indexed amount); event DirectlyDeposited(address indexed from, uint indexed amount); event Gave (uint indexed giftId, address indexed giver, address indexed recipient, uint amount, uint expiry); event Redeemed (uint indexed giftId, address indexed giver, address indexed recipient, uint amount); event CollectedAllFees (address indexed by, uint indexed amount); event ReturnedToGiver (uint indexed giftId); event ChangedRecipient (uint indexed giftId, address indexed originalRecipient, address indexed newRecipient); event ClaimedRefund(address by, uint indexed amount, uint indexed giftId); event AllowedRefunds(address indexed by); event DisallowedRefunds(address indexed by); // Constructor function BuggyContract() public payable { refundsAllowed = false; // disallow refunds by default Constructed(msg.sender, msg.value); } // Fallback function which allows this contract to receive funds. function () public payable { // Sending ETH directly to this contract does nothing except log an // event. DirectlyDeposited(msg.sender, msg.value); } //// Getter functions: function getFeesCollected () public onlyOwner view returns (uint) { return feesCollected; } function doesGiftExist (uint giftId) public view returns (bool) { return giftIdToGift[giftId].exists; } function getGiftGiver (uint giftId) public view returns (address) { return giftIdToGift[giftId].giver; } function getGiftRecipient (uint giftId) public view returns (address) { return giftIdToGift[giftId].recipient; } function getGiftAmount (uint giftId) public view returns (uint) { return giftIdToGift[giftId].amount; } function getGiftExpiry (uint giftId) public view returns (uint) { return giftIdToGift[giftId].expiry; } function isGiftRedeemed (uint giftId) public view returns (bool) { return giftIdToGift[giftId].redeemed; } function isGiftReturned (uint giftId) public view returns (bool) { return giftIdToGift[giftId].returned; } function isGiftRefunded (uint giftId) public view returns (bool) { return giftIdToGift[giftId].refunded; } function getGiftIdsByRecipient (address recipient) public view returns (uint[]) { return recipientToGiftIds[recipient]; } //// Contract functions: // Call this function while sending ETH to give a gift. // @recipient: the recipient's address // @expiry: the Unix timestamp of the expiry datetime. // Tested in test/test_give.js and test/TestGive.sol function give (address recipient, uint expiry) public payable returns (uint) { address giver = msg.sender; // Validate the giver address assert(giver != address(0)); // The gift must be a positive amount of ETH uint amount = msg.value; require(amount > 0); // The expiry datetime must be in the future. It is fine to use the // block timestamp in this contract because the possible drift is // only 12 minutes. See: https://consensys.github.io // /smart-contract-best-practices/recommendations/#timestamp-dependence require(expiry > now); // The giver and the recipient must be different addresses require(giver != recipient); // The recipient must be a valid address require(recipient != address(0)); // Make sure nextGiftId is 0 or positive, or this contract is buggy assert(nextGiftId >= 0); // Append the gift to the mapping recipientToGiftIds[recipient].push(nextGiftId); // Calculate the contract owner's fee uint feeTaken = fee(amount); assert(feeTaken >= 0); // Increment feesCollected feesCollected = SafeMath.add(feesCollected, feeTaken); // Shave off the fee uint amtGiven = SafeMath.sub(amount, feeTaken); assert(amtGiven > 0); // If a gift with this new gift ID already exists, this contract is buggy. assert(giftIdToGift[nextGiftId].exists == false); // Update the giftIdToGift mapping with the new gift giftIdToGift[nextGiftId] = Gift(true, nextGiftId, giver, recipient, expiry, amtGiven, false, false, false); uint giftId = nextGiftId; // Increment nextGiftId nextGiftId = SafeMath.add(giftId, 1); // If a gift with this new gift ID already exists, this contract is buggy. assert(giftIdToGift[nextGiftId].exists == false); // Log the event Gave(giftId, giver, recipient, amount, expiry); return giftId; } // Call this function to redeem a gift of ETH. // Tested in test/test_redeem.js function redeem (uint giftId, uint amount) public { // The giftID should be 0 or positive require(giftId >= 0); // The gift must exist require(giftIdToGift[giftId].exists == true); // The gift must exist and must not have already been redeemed, returned, or refunded require(isValidGift(giftIdToGift[giftId])); // The recipient must be the caller of this function address recipient = giftIdToGift[giftId].recipient; require(recipient == msg.sender); // The current datetime must be after the expiry datetime require(now > giftIdToGift[giftId].expiry); //// If the following assert statements are triggered, this contract is //// buggy. // The amount must be positive because this is required in give() assert(amount > 0); // The giver must not be the recipient because this was asserted in give() address giver = giftIdToGift[giftId].giver; assert(giver != recipient); // Make sure the giver is valid because this was asserted in give(); assert(giver != address(0)); // Update the gift to mark it as redeemed, so that the funds cannot be // double-spent giftIdToGift[giftId].redeemed = true; // Transfer the funds recipient.transfer(amount); // Log the event Redeemed(giftId, giftIdToGift[giftId].giver, recipient, amount); } // Calculate the contract owner's fee // Tested in test/test_fee.js function fee (uint amount) public pure returns (uint) { if (amount < 0.01 ether) { return 0; } else if (amount >= 0.01 ether && amount < 0.1 ether) { return SafeMath.div(amount, 100000); } else if (amount >= 0.1 ether && amount < 1 ether) { return SafeMath.div(amount, 10000); } else if (amount >= 1 ether) { return SafeMath.div(amount, 1000); } } // Transfer the fees collected thus far to the contract owner. // Only the contract owner may invoke this function. // Tested in test/test_collect_fees.js function collectAllFees () public onlyOwner { // Store the fee amount in a temporary variable uint amount = feesCollected; // Make sure that the amount is positive require(amount > 0); // Set the feesCollected state variable to 0 feesCollected = 0; // Make the transfer owner.transfer(amount); CollectedAllFees(owner, amount); } // A recipient may change the recipient address of a Gift // Tested in test/test_change_recipient.js and test_update_recipient_to_giftids.js function changeRecipient (address newRecipient, uint giftId) public { // Validate the giftId require(giftId >= 0); // Validate the new recipient address require(newRecipient != address(0)); // The gift must exist and must not have already been redeemed, returned, or refunded require(isValidGift(giftIdToGift[giftId])); // Only allow an the existing recipient of the gift with giftId to // change the recipient address currentRecipient = giftIdToGift[giftId].recipient; require(msg.sender == currentRecipient); // The giver must not be the recipient because this is required in give() and redeem() address giver = giftIdToGift[giftId].giver; require(giver != newRecipient); // Make sure the new recipient is not the same as the existing one require(currentRecipient != newRecipient); // Update the gift giftIdToGift[giftId].recipient = newRecipient; // Make sure that the exisiting recipient is in the recipientToGiftIds mapping require(recipientToGiftIds[msg.sender].length > 0); // Update the recipientToGiftIds mapping. This is slightly tricky. // First, remove the gift from the mapping for the old recipient. // If the giftId is the last element of the array, deleting it is // straightforward: uint len = recipientToGiftIds[msg.sender].length; bool success = false; if (recipientToGiftIds[msg.sender][len-1] == giftId) { // Just delete the last element delete recipientToGiftIds[msg.sender][len-1]; // Decrement the array length recipientToGiftIds[msg.sender].length--; // For the assert stmt later on success = true; } else { // Otherwise, find its index (i), replace it with the last element, and // then delete the last element for (uint i=0; i < len-1; i++) { if (recipientToGiftIds[msg.sender][i] == giftId) { // Replace the found item at [i] with the last element uint lastGiftId = recipientToGiftIds[msg.sender][len-1]; recipientToGiftIds[msg.sender][i] = lastGiftId; // For the assert stmt later on success = true; break; } } } // Make sure the removal worked and make sure the array length is // smaller by 1 assert(success == true); assert(len-1 == recipientToGiftIds[msg.sender].length); // Finally, append the giftId to the array in the mapping for the new recipient recipientToGiftIds[newRecipient].push(giftId); // Log the event ChangedRecipient(giftId, msg.sender, newRecipient); } // A recipient may choose to return the funds to the giver at any time // Tested by test/test_return_to_giver.js function returnToGiver (uint giftId) public { // Validate the giftId require(giftId >= 0); // The gift must exist and must not have already been redeemed, returned, or refunded require(isValidGift(giftIdToGift[giftId])); // Only the recipient can return funds to the giver require(giftIdToGift[giftId].recipient == msg.sender); // Only allow a positive fund transfer require(giftIdToGift[giftId].amount > 0); // Make sure the giver's address is valid as this is asserted in give() and redeem(): assert(giftIdToGift[giftId].giver != address(0)); // Update the gift data giftIdToGift[giftId].returned = true; // Make the transfer giftIdToGift[giftId].giver.transfer(giftIdToGift[giftId].amount); // Log the event ReturnedToGiver(giftId); } // This function should only be called in the unlikey situation where the // funds have to be returned to all givers. Refunds are only possible if // the expiry datetime has not passed. // Tested by test/test_refund.js function claimRefund(uint giftId) public { // Only allow a refund if allowRefunds() has been invoked require(refundsAllowed == true); // The gift must exist and must not have already been redeemed, returned, or refunded require(isValidGift(giftIdToGift[giftId])); // Only the gift giver can call this function address giver = giftIdToGift[giftId].giver; require(giver == msg.sender); // Make sure the giver's address is valid as this is asserted in give() and redeem(): assert(giftIdToGift[giftId].giver != address(0)); // Only transfer positive amounts uint amount = giftIdToGift[giftId].amount; require(amount > 0); // Only allow refunds before the expiry require(giftIdToGift[giftId].expiry > now); // Mark the gift as refunded giftIdToGift[giftId].refunded = true; // Make the transfer giver.transfer(amount); // Log this event ClaimedRefund(giver, amount, giftId); } // Only call this in the event that givers should be allowed to get their funds back function allowRefunds () public onlyOwner { refundsAllowed = true; AllowedRefunds(owner); // Log the event } // Reverse allowRefunds() function disallowRefunds () public onlyOwner { refundsAllowed = false; DisallowedRefunds(owner); // Log the event } // Returns true only if the gift exists and has not already been // redeemed, returned, or refunded function isValidGift(Gift gift) private pure returns (bool) { return gift.exists == true && gift.redeemed == false && gift.returned == false && gift.refunded == false; } }
This function should only be called in the unlikey situation where the funds have to be returned to all givers. Refunds are only possible if the expiry datetime has not passed. Tested by test/test_refund.js Only allow a refund if allowRefunds() has been invoked The gift must exist and must not have already been redeemed, returned, or refunded Only the gift giver can call this function Make sure the giver's address is valid as this is asserted in give() and redeem(): Only transfer positive amounts Only allow refunds before the expiry Mark the gift as refunded Make the transfer Log this event
function claimRefund(uint giftId) public { require(refundsAllowed == true); require(isValidGift(giftIdToGift[giftId])); address giver = giftIdToGift[giftId].giver; require(giver == msg.sender); assert(giftIdToGift[giftId].giver != address(0)); uint amount = giftIdToGift[giftId].amount; require(amount > 0); require(giftIdToGift[giftId].expiry > now); giftIdToGift[giftId].refunded = true; giver.transfer(amount); ClaimedRefund(giver, amount, giftId); }
12,588,830
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract HotPotato is ERC721, ERC721Enumerable, Ownable { using Counters for Counters.Counter; event Burn(address indexed owner, uint256 indexed tokenId); Counters.Counter private _tokenIdCounter; Counters.Counter private _tokenTypeCounter; mapping(uint256 => uint256) public lastTossed; mapping(uint256 => uint256) public tokenIdToType; mapping(uint256 => string) public tokenTypeToURI; uint256 public mintFee = 0.00001 ether; uint256 public burnFee = 0.00001 ether; uint256 public hotDuration = 1 days; constructor() ERC721("HotPotato", "HOT") {} function setFees(uint256 _mintFee, uint256 _burnFee) public onlyOwner { mintFee = _mintFee; burnFee = _burnFee; } function setHotDuration(uint256 _hotDuration) public onlyOwner { hotDuration = _hotDuration; } function addType(string memory _uri) public onlyOwner { uint256 tokenType = _tokenTypeCounter.current(); tokenTypeToURI[tokenType] = _uri; _tokenTypeCounter.increment(); } function updateType(uint256 _type, string memory _uri) public onlyOwner { require(_type < _tokenTypeCounter.current(), "Nonexistent token type"); tokenTypeToURI[_type] = _uri; } function safeMint(uint256 _type, address to) public payable { require(msg.value == mintFee, "Incorrect mint fee"); require(_type < _tokenTypeCounter.current(), "Nonexistent token type"); uint256 tokenId = _tokenIdCounter.current(); lastTossed[tokenId] = block.timestamp; tokenIdToType[tokenId] = _type; _safeMint(_msgSender(), tokenId); // Immediately toss to `address` if it's different from the minter. if (_msgSender() != to) { _transfer(_msgSender(), to, tokenId); } _tokenIdCounter.increment(); } function isHot(uint256 tokenId) public view returns (bool) { require(lastTossed[tokenId] != 0, "isHot query for nonexistent token"); return (block.timestamp - lastTossed[tokenId]) < hotDuration; } function burn(uint256 tokenId) public payable { address owner = ERC721.ownerOf(tokenId); require(_msgSender() == owner, "burn caller is not owner"); require(msg.value == burnFee, "Incorrect burn fee"); _burn(tokenId); lastTossed[tokenId] = 0; tokenIdToType[tokenId] = 0; emit Burn(owner, tokenId); } function withdrawFees() public onlyOwner { (bool sent, ) = msg.sender.call{value: address(this).balance}(""); require(sent, "Failed to send collected fees"); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { require(isHot(tokenId), "Cannot transfer cold potato"); lastTossed[tokenId] = block.timestamp; super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); uint256 tokenType = tokenIdToType[tokenId]; return tokenTypeToURI[tokenType]; } }
Immediately toss to `address` if it's different from the minter.
function safeMint(uint256 _type, address to) public payable { require(msg.value == mintFee, "Incorrect mint fee"); require(_type < _tokenTypeCounter.current(), "Nonexistent token type"); uint256 tokenId = _tokenIdCounter.current(); lastTossed[tokenId] = block.timestamp; tokenIdToType[tokenId] = _type; _safeMint(_msgSender(), tokenId); if (_msgSender() != to) { _transfer(_msgSender(), to, tokenId); } _tokenIdCounter.increment(); }
2,535,674
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Rockstar * @dev Script to deploy batch transactions of NFTs */ contract BatchTransferPUSH is Ownable { constructor() public {} /** * @notice Mass transfers Tokens in a batched transaction * @param token the address of the NFT token that needs to be mintedd * @param recipients the array of address of recipients who will receive these tokens * @param amounts the array of amounts to be transferred * @param startpos the start position in NFT order * @param num the number of tokens to be minted */ function transferPUSH(address token, address[] memory recipients, uint256[] memory amounts, uint256 startpos, uint256 num) public onlyOwner { // require(recipients.length == 100, "BatchDeploy::batchDeployNFTs: Needs exact 100 recipients"); require(recipients.length == amounts.length, "BatchTransferPUSH::transferPUSH: recipients and amounts count mismatch"); IERC20 pushToken = IERC20(token); for (uint i=startpos; i<num; i++) { // Send Tokens pushToken.transfer(recipients[i], amounts[i]); } } /** * @notice Mass transfers Tokens in a batched transaction * @param token the address of the ERC20 token that needs to be transferred * @param amount the amount to be transferred */ function withdrawTokens(address token, uint256 amount) public onlyOwner { IERC20 pushToken = IERC20(token); pushToken.transfer(owner(), amount); } } // 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 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.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; } }
Mass transfers Tokens in a batched transaction token the address of the NFT token that needs to be mintedd recipients the array of address of recipients who will receive these tokens amounts the array of amounts to be transferred startpos the start position in NFT order num the number of tokens to be minted/ require(recipients.length == 100, "BatchDeploy::batchDeployNFTs: Needs exact 100 recipients"); Send Tokens
function transferPUSH(address token, address[] memory recipients, uint256[] memory amounts, uint256 startpos, uint256 num) public onlyOwner { require(recipients.length == amounts.length, "BatchTransferPUSH::transferPUSH: recipients and amounts count mismatch"); IERC20 pushToken = IERC20(token); for (uint i=startpos; i<num; i++) { pushToken.transfer(recipients[i], amounts[i]); } }
14,755,994
./full_match/5/0x32ff4D05236E95FF60299E9b7BaB351179138389/sources/contracts/core/Factory.sol
@inheritdoc IFactory
function isWhitelistedNFTManager(address sender) external view override returns (bool) { if (whitelistDisabled) return true; return whitelistedNFTManagers.contains(sender); }
1,940,570
// Bitcoin transaction parsing library // Copyright 2016 rain <https://keybase.io/rain> // // 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. // https://en.bitcoin.it/wiki/Protocol_documentation#tx // // Raw Bitcoin transaction structure: // // field | size | type | description // version | 4 | int32 | transaction version number // n_tx_in | 1-9 | var_int | number of transaction inputs // tx_in | 41+ | tx_in[] | list of transaction inputs // n_tx_out | 1-9 | var_int | number of transaction outputs // tx_out | 9+ | tx_out[] | list of transaction outputs // lock_time | 4 | uint32 | block number / timestamp at which tx locked // // Transaction input (tx_in) structure: // // field | size | type | description // previous | 36 | outpoint | Previous output transaction reference // script_len | 1-9 | var_int | Length of the signature script // sig_script | ? | uchar[] | Script for confirming transaction authorization // sequence | 4 | uint32 | Sender transaction version // // OutPoint structure: // // field | size | type | description // hash | 32 | char[32] | The hash of the referenced transaction // index | 4 | uint32 | The index of this output in the referenced transaction // // Transaction output (tx_out) structure: // // field | size | type | description // value | 8 | int64 | Transaction value (Satoshis) // pk_script_len | 1-9 | var_int | Length of the public key script // pk_script | ? | uchar[] | Public key as a Bitcoin script. // // Variable integers (var_int) can be encoded differently depending // on the represented value, to save space. Variable integers always // precede an array of a variable length data type (e.g. tx_in). // // Variable integer encodings as a function of represented value: // // value | bytes | format // <0xFD (253) | 1 | uint8 // <=0xFFFF (65535)| 3 | 0xFD followed by length as uint16 // <=0xFFFF FFFF | 5 | 0xFE followed by length as uint32 // - | 9 | 0xFF followed by length as uint64 // // Public key scripts `pk_script` are set on the output and can // take a number of forms. The regular transaction script is // called 'pay-to-pubkey-hash' (P2PKH): // // OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG // // OP_x are Bitcoin script opcodes. The bytes representation (including // the 0x14 20-byte stack push) is: // // 0x76 0xA9 0x14 <pubKeyHash> 0x88 0xAC // // The <pubKeyHash> is the ripemd160 hash of the sha256 hash of // the public key, preceded by a network version byte. (21 bytes total) // // Network version bytes: 0x00 (mainnet); 0x6f (testnet); 0x34 (namecoin) // // The Bitcoin address is derived from the pubKeyHash. The binary form is the // pubKeyHash, plus a checksum at the end. The checksum is the first 4 bytes // of the (32 byte) double sha256 of the pubKeyHash. (25 bytes total) // This is converted to base58 to form the publicly used Bitcoin address. // Mainnet P2PKH transaction scripts are to addresses beginning with '1'. // // P2SH ('pay to script hash') scripts only supply a script hash. The spender // must then provide the script that would allow them to redeem this output. // This allows for arbitrarily complex scripts to be funded using only a // hash of the script, and moves the onus on providing the script from // the spender to the redeemer. // // The P2SH script format is simple: // // OP_HASH160 <scriptHash> OP_EQUAL // // 0xA9 0x14 <scriptHash> 0x87 // // The <scriptHash> is the ripemd160 hash of the sha256 hash of the // redeem script. The P2SH address is derived from the scriptHash. // Addresses are the scriptHash with a version prefix of 5, encoded as // Base58check. These addresses begin with a '3'. pragma solidity ^0.5.10; // parse a raw bitcoin transaction byte array library BtcParser { // Convert a variable integer into something useful and return it and // the index to after it. function parseVarInt(bytes memory txBytes, uint pos) public returns (uint, uint) { // the first byte tells us how big the integer is uint8 ibit = uint8(txBytes[pos]); pos += 1; // skip ibit if (ibit < 0xfd) { return (ibit, pos); } else if (ibit == 0xfd) { return (getBytesLE(txBytes, pos, 16), pos + 2); } else if (ibit == 0xfe) { return (getBytesLE(txBytes, pos, 32), pos + 4); } else if (ibit == 0xff) { return (getBytesLE(txBytes, pos, 64), pos + 8); } } // convert little endian bytes to uint function getBytesLE(bytes memory data, uint pos, uint bits) public returns (uint) { if (bits == 8) { return uint8(data[pos]); } else if (bits == 16) { return uint16(uint8(data[pos])) + uint16(uint8(data[pos + 1])) * 2 ** 8; } else if (bits == 32) { return uint32(uint8(data[pos])) + uint32(uint8(data[pos + 1])) * 2 ** 8 + uint32(uint8(data[pos + 2])) * 2 ** 16 + uint32(uint8(data[pos + 3])) * 2 ** 24; } else if (bits == 64) { return uint64(uint8(data[pos])) + uint64(uint8(data[pos + 1])) * 2 ** 8 + uint64(uint8(data[pos + 2])) * 2 ** 16 + uint64(uint8(data[pos + 3])) * 2 ** 24 + uint64(uint8(data[pos + 4])) * 2 ** 32 + uint64(uint8(data[pos + 5])) * 2 ** 40 + uint64(uint8(data[pos + 6])) * 2 ** 48 + uint64(uint8(data[pos + 7])) * 2 ** 56; } } // scan the full transaction bytes and return the first two output // values (in satoshis) and addresses (in binary) function getFirstTwoOutputs(bytes memory txBytes) public returns (uint, bytes20, uint, bytes20) { uint pos; uint[] memory input_script_lens = new uint[](2); uint[] memory output_script_lens = new uint[](2); uint[] memory script_starts = new uint[](2); uint[] memory output_values = new uint[](2); bytes20[] memory output_addresses = new bytes20[](2); pos = 4; // skip version (input_script_lens, pos) = scanInputs(txBytes, pos, 0); (output_values, script_starts, output_script_lens, pos) = scanOutputs(txBytes, pos, 2); for (uint i = 0; i < 2; i++) { bytes20 pkhash = parseOutputScript(txBytes, script_starts[i], output_script_lens[i]); output_addresses[i] = pkhash; } return (output_values[0], output_addresses[0], output_values[1], output_addresses[1]); } // Check whether `btcAddress` is in the transaction outputs *and* // whether *at least* `value` has been sent to it. function checkValueSent(bytes memory txBytes, bytes20 btcAddress, uint value) public returns (bool) { uint pos = 4; // skip version (, pos) = scanInputs(txBytes, pos, 0); // find end of inputs // scan *all* the outputs and find where they are (uint[] memory output_values, uint[] memory script_starts, uint[] memory output_script_lens,) = scanOutputs(txBytes, pos, 0); // look at each output and check whether it at least value to btcAddress for (uint i = 0; i < output_values.length; i++) { bytes20 pkhash = parseOutputScript(txBytes, script_starts[i], output_script_lens[i]); if (pkhash == btcAddress && output_values[i] >= value) { return true; } } } // scan the inputs and find the script lengths. // return an array of script lengths and the end position // of the inputs. // takes a 'stop' argument which sets the maximum number of // outputs to scan through. stop=0 => scan all. function scanInputs(bytes memory txBytes, uint pos, uint stop) public returns (uint[] memory, uint) { uint n_inputs; uint halt; uint script_len; (n_inputs, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_inputs) { halt = n_inputs; } else { halt = stop; } uint[] memory script_lens = new uint[](halt); for (uint8 i = 0; i < halt; i++) { pos += 36; // skip outpoint (script_len, pos) = parseVarInt(txBytes, pos); script_lens[i] = script_len; pos += script_len + 4; // skip sig_script, seq } return (script_lens, pos); } // scan the outputs and find the values and script lengths. // return array of values, array of script lengths and the // end position of the outputs. // takes a 'stop' argument which sets the maximum number of // outputs to scan through. stop=0 => scan all. function scanOutputs(bytes memory txBytes, uint pos, uint stop) public returns ( uint[] memory, uint[] memory, uint[] memory, uint) { uint n_outputs; uint halt; uint script_len; (n_outputs, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_outputs) { halt = n_outputs; } else { halt = stop; } uint[] memory script_starts = new uint[](halt); uint[] memory script_lens = new uint[](halt); uint[] memory output_values = new uint[](halt); for (uint i = 0; i < halt; i++) { output_values[i] = getBytesLE(txBytes, pos, 64); pos += 8; (script_len, pos) = parseVarInt(txBytes, pos); script_starts[i] = pos; script_lens[i] = script_len; pos += script_len; } return (output_values, script_starts, script_lens, pos); } // Slice 20 contiguous bytes from bytes `data`, starting at `start` function sliceBytes20(bytes memory data, uint start) public returns (bytes20) { uint160 slice = 0; for (uint160 i = 0; i < 20; i++) { slice += uint160(uint8(data[i + start])) << (8 * (19 - i)); } return bytes20(slice); } // returns true if the bytes located in txBytes by pos and // script_len represent a P2PKH script function isP2PKH(bytes memory txBytes, uint pos, uint script_len) public returns (bool) { return (script_len == 25) // 20 byte pubkeyhash + 5 bytes of script && (txBytes[pos] == 0x76) // OP_DUP && (txBytes[pos + 1] == 0xa9) // OP_HASH160 && (txBytes[pos + 2] == 0x14) // bytes to push && (txBytes[pos + 23] == 0x88) // OP_EQUALVERIFY && (txBytes[pos + 24] == 0xac); // OP_CHECKSIG } // returns true if the bytes located in txBytes by pos and // script_len represent a P2SH script function isP2SH(bytes memory txBytes, uint pos, uint script_len) public returns (bool) { return (script_len == 23) // 20 byte scripthash + 3 bytes of script && (txBytes[pos + 0] == 0xa9) // OP_HASH160 && (txBytes[pos + 1] == 0x14) // bytes to push && (txBytes[pos + 22] == 0x87); // OP_EQUAL } // Get the pubkeyhash / scripthash from an output script. Assumes // pay-to-pubkey-hash (P2PKH) or pay-to-script-hash (P2SH) outputs. // Returns the pubkeyhash/ scripthash, or zero if unknown output. function parseOutputScript(bytes memory txBytes, uint pos, uint script_len) public returns (bytes20) { if (isP2PKH(txBytes, pos, script_len)) { return sliceBytes20(txBytes, pos + 3); } else if (isP2SH(txBytes, pos, script_len)) { return sliceBytes20(txBytes, pos + 2); } else { return bytes20(0); } } //NOTE: Only supports segwit txs //https://bitcoin.stackexchange.com/questions/79723/where-is-the-pubkey-for-segwit-inputs //if multisig, it will just grab the first pubkey function getPubKeyFromTx(bytes memory txBytes) public returns(bytes memory) { uint pos = 0; bytes memory pubkey; for(uint i = 0; i < txBytes.length; i++) { //byte with value 0x21 is used to show the start of the pubkey in the raw tx if(txBytes[i] == 0x21) { pos = i + 1; break; } } uint index = 0; for(uint i = pos; i < pos + 33; i++) { pubkey[index] = txBytes[i]; index++; } return pubkey; } function getSegtwitSignature(bytes memory txBytes) public returns(bytes memory) { uint pos = 0; bytes memory signature; for(uint i = 0; i < txBytes.length; i++) { //byte with value 0x47 is used to show the start of the signature in the raw tx if(txBytes[i] == 0x47) { pos = i + 1; break; } } uint index = 0; for(uint i = pos; i < pos + 71; i++) { signature[index] = txBytes[i]; index++; } return signature; } }
Slice 20 contiguous bytes from bytes `data`, starting at `start`
function sliceBytes20(bytes memory data, uint start) public returns (bytes20) { uint160 slice = 0; for (uint160 i = 0; i < 20; i++) { slice += uint160(uint8(data[i + start])) << (8 * (19 - i)); } return bytes20(slice); }
12,672,458
pragma solidity 0.5.9; import "./Asset/ERC1155ERC721.sol"; contract Asset is ERC1155ERC721 {} pragma solidity 0.5.9; import "../contracts_common/Interfaces/ERC1155.sol"; import "../contracts_common/Interfaces/ERC1155TokenReceiver.sol"; import "../contracts_common/Libraries/AddressUtils.sol"; import "../contracts_common/Libraries/ObjectLib32.sol"; import "../contracts_common/Interfaces/ERC721.sol"; import "../contracts_common/Interfaces/ERC721TokenReceiver.sol"; import "../contracts_common/BaseWithStorage/SuperOperators.sol"; contract ERC1155ERC721 is SuperOperators, ERC1155, ERC721 { using AddressUtils for address; using ObjectLib32 for ObjectLib32.Operations; using ObjectLib32 for uint256; bytes4 private constant ERC1155_IS_RECEIVER = 0x4e2312e0; bytes4 private constant ERC1155_RECEIVED = 0xf23a6e61; bytes4 private constant ERC1155_BATCH_RECEIVED = 0xbc197c81; bytes4 private constant ERC721_RECEIVED = 0x150b7a02; uint256 private constant CREATOR_OFFSET_MULTIPLIER = uint256(2)**(256 - 160); uint256 private constant IS_NFT_OFFSET_MULTIPLIER = uint256(2)**(256 - 160 - 1); uint256 private constant PACK_ID_OFFSET_MULTIPLIER = uint256(2)**(256 - 160 - 1 - 32 - 40); uint256 private constant PACK_NUM_FT_TYPES_OFFSET_MULTIPLIER = uint256(2)**(256 - 160 - 1 - 32 - 40 - 12); uint256 private constant NFT_INDEX_OFFSET = 63; uint256 private constant IS_NFT = 0x0000000000000000000000000000000000000000800000000000000000000000; uint256 private constant NOT_IS_NFT = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFFFFFFFFFFF; uint256 private constant NFT_INDEX = 0x00000000000000000000000000000000000000007FFFFFFF8000000000000000; uint256 private constant NOT_NFT_INDEX = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF800000007FFFFFFFFFFFFFFF; uint256 private constant URI_ID = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000007FFFFFFFFFFFF800; uint256 private constant PACK_ID = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000007FFFFFFFFF800000; uint256 private constant PACK_INDEX = 0x00000000000000000000000000000000000000000000000000000000000007FF; uint256 private constant PACK_NUM_FT_TYPES = 0x00000000000000000000000000000000000000000000000000000000007FF800; uint256 private constant MAX_SUPPLY = uint256(2)**32 - 1; uint256 private constant MAX_PACK_SIZE = uint256(2)**11; event CreatorshipTransfer(address indexed original, address indexed from, address indexed to); mapping(address => uint256) private _numNFTPerAddress; // erc721 mapping(uint256 => uint256) private _owners; // erc721 mapping(address => mapping(uint256 => uint256)) private _packedTokenBalance; // erc1155 mapping(address => mapping(address => bool)) private _operatorsForAll; // erc721 and erc1155 mapping(uint256 => address) private _erc721operators; // erc721 mapping(uint256 => bytes32) private _metadataHash; // erc721 and erc1155 mapping(uint256 => bytes) private _rarityPacks; // rarity configuration per packs (2 bits per Asset) mapping(uint256 => uint32) private _nextCollectionIndex; // extraction mapping(address => address) private _creatorship; // creatorship transfer mapping(address => bool) private _bouncers; // the contracts allowed to mint mapping(address => bool) private _metaTransactionContracts; // native meta-transaction support address private _bouncerAdmin; bool internal _init; function init( address metaTransactionContract, address admin, address bouncerAdmin ) public { require(!_init, "ALREADY_INITIALISED"); _init = true; _metaTransactionContracts[metaTransactionContract] = true; _admin = admin; _bouncerAdmin = bouncerAdmin; emit MetaTransactionProcessor(metaTransactionContract, true); } event BouncerAdminChanged(address oldBouncerAdmin, address newBouncerAdmin); /// @notice Returns the current administrator in charge of minting rights. /// @return the current minting administrator in charge of minting rights. function getBouncerAdmin() external view returns (address) { return _bouncerAdmin; } /// @notice Change the minting administrator to be `newBouncerAdmin`. /// @param newBouncerAdmin address of the new minting administrator. function changeBouncerAdmin(address newBouncerAdmin) external { require(msg.sender == _bouncerAdmin, "only bouncerAdmin can change itself"); emit BouncerAdminChanged(_bouncerAdmin, newBouncerAdmin); _bouncerAdmin = newBouncerAdmin; } event Bouncer(address bouncer, bool enabled); /// @notice Enable or disable the ability of `bouncer` to mint tokens (minting bouncer rights). /// @param bouncer address that will be given/removed minting bouncer rights. /// @param enabled set whether the address is enabled or disabled as a minting bouncer. function setBouncer(address bouncer, bool enabled) external { require(msg.sender == _bouncerAdmin, "only bouncerAdmin can setup bouncers"); _bouncers[bouncer] = enabled; emit Bouncer(bouncer, enabled); } /// @notice check whether address `who` is given minting bouncer rights. /// @param who The address to query. /// @return whether the address has minting rights. function isBouncer(address who) external view returns (bool) { return _bouncers[who]; } event MetaTransactionProcessor(address metaTransactionProcessor, bool enabled); /// @notice Enable or disable the ability of `metaTransactionProcessor` to perform meta-tx (metaTransactionProcessor rights). /// @param metaTransactionProcessor address that will be given/removed metaTransactionProcessor rights. /// @param enabled set whether the metaTransactionProcessor is enabled or disabled. function setMetaTransactionProcessor(address metaTransactionProcessor, bool enabled) external { require(msg.sender == _admin, "only admin can setup metaTransactionProcessors"); _metaTransactionContracts[metaTransactionProcessor] = enabled; emit MetaTransactionProcessor(metaTransactionProcessor, enabled); } /// @notice check whether address `who` is given meta-transaction execution rights. /// @param who The address to query. /// @return whether the address has meta-transaction execution rights. function isMetaTransactionProcessor(address who) external view returns (bool) { return _metaTransactionContracts[who]; } /// @notice Mint a token type for `creator` on slot `packId`. /// @param creator address of the creator of the token. /// @param packId unique packId for that token. /// @param hash hash of an IPFS cidv1 folder that contains the metadata of the token type in the file 0.json. /// @param supply number of tokens minted for that token type. /// @param rarity rarity power of the token. /// @param owner address that will receive the tokens. /// @param data extra data to accompany the minting call. /// @return the id of the newly minted token type. function mint( address creator, uint40 packId, bytes32 hash, uint256 supply, uint8 rarity, address owner, bytes calldata data ) external returns (uint256 id) { require(hash != 0, "hash is zero"); require(_bouncers[msg.sender], "only bouncer allowed to mint"); require(owner != address(0), "destination is zero address"); id = generateTokenId(creator, supply, packId, supply == 1 ? 0 : 1, 0); _mint(hash, supply, rarity, msg.sender, owner, id, data, false); } function generateTokenId( address creator, uint256 supply, uint40 packId, uint16 numFTs, uint16 packIndex ) internal pure returns (uint256) { require(supply > 0 && supply <= MAX_SUPPLY, "invalid supply"); return uint256(creator) * CREATOR_OFFSET_MULTIPLIER + // CREATOR (supply == 1 ? uint256(1) * IS_NFT_OFFSET_MULTIPLIER : 0) + // minted as NFT (1) or FT (0) // IS_NFT uint256(packId) * PACK_ID_OFFSET_MULTIPLIER + // packId (unique pack) // PACk_ID numFTs * PACK_NUM_FT_TYPES_OFFSET_MULTIPLIER + // number of fungible token in the pack // PACK_NUM_FT_TYPES packIndex; // packIndex (position in the pack) // PACK_INDEX } function _mint( bytes32 hash, uint256 supply, uint8 rarity, address operator, address owner, uint256 id, bytes memory data, bool extraction ) internal { uint256 uriId = id & URI_ID; if (!extraction) { require(uint256(_metadataHash[uriId]) == 0, "id already used"); _metadataHash[uriId] = hash; require(rarity < 4, "rarity >= 4"); bytes memory pack = new bytes(1); pack[0] = bytes1(rarity * 64); _rarityPacks[uriId] = pack; } if (supply == 1) { // ERC721 _numNFTPerAddress[owner]++; _owners[id] = uint256(owner); emit Transfer(address(0), owner, id); } else { (uint256 bin, uint256 index) = id.getTokenBinIndex(); _packedTokenBalance[owner][bin] = _packedTokenBalance[owner][bin].updateTokenBalance( index, supply, ObjectLib32.Operations.REPLACE ); } emit TransferSingle(operator, address(0), owner, id, supply); require( _checkERC1155AndCallSafeTransfer(operator, address(0), owner, id, supply, data, false, false), "transfer rejected" ); } /// @notice Mint multiple token types for `creator` on slot `packId`. /// @param creator address of the creator of the tokens. /// @param packId unique packId for the tokens. /// @param hash hash of an IPFS cidv1 folder that contains the metadata of each token type in the files: 0.json, 1.json, 2.json, etc... /// @param supplies number of tokens minted for each token type. /// @param rarityPack rarity power of each token types packed into 2 bits each. /// @param owner address that will receive the tokens. /// @param data extra data to accompany the minting call. /// @return the ids of each newly minted token types. function mintMultiple( address creator, uint40 packId, bytes32 hash, uint256[] calldata supplies, bytes calldata rarityPack, address owner, bytes calldata data ) external returns (uint256[] memory ids) { require(hash != 0, "hash is zero"); require(_bouncers[msg.sender], "only bouncer allowed to mint"); require(owner != address(0), "destination is zero address"); uint16 numNFTs; (ids, numNFTs) = allocateIds(creator, supplies, rarityPack, packId, hash); _mintBatches(supplies, owner, ids, numNFTs); completeMultiMint(msg.sender, owner, ids, supplies, data); } function allocateIds( address creator, uint256[] memory supplies, bytes memory rarityPack, uint40 packId, bytes32 hash ) internal returns (uint256[] memory ids, uint16 numNFTs) { require(supplies.length > 0, "supplies.length == 0"); require(supplies.length <= MAX_PACK_SIZE, "too big batch"); (ids, numNFTs) = generateTokenIds(creator, supplies, packId); uint256 uriId = ids[0] & URI_ID; require(uint256(_metadataHash[uriId]) == 0, "id already used"); _metadataHash[uriId] = hash; _rarityPacks[uriId] = rarityPack; } function generateTokenIds( address creator, uint256[] memory supplies, uint40 packId ) internal pure returns (uint256[] memory, uint16) { uint16 numTokenTypes = uint16(supplies.length); uint256[] memory ids = new uint256[](numTokenTypes); uint16 numNFTs = 0; for (uint16 i = 0; i < numTokenTypes; i++) { if (numNFTs == 0) { if (supplies[i] == 1) { numNFTs = uint16(numTokenTypes - i); } } else { require(supplies[i] == 1, "NFTs need to be put at the end"); } } uint16 numFTs = numTokenTypes - numNFTs; for (uint16 i = 0; i < numTokenTypes; i++) { ids[i] = generateTokenId(creator, supplies[i], packId, numFTs, i); } return (ids, numNFTs); } function completeMultiMint( address operator, address owner, uint256[] memory ids, uint256[] memory supplies, bytes memory data ) internal { emit TransferBatch(operator, address(0), owner, ids, supplies); require( _checkERC1155AndCallSafeBatchTransfer(operator, address(0), owner, ids, supplies, data), "transfer rejected" ); } function _mintBatches( uint256[] memory supplies, address owner, uint256[] memory ids, uint16 numNFTs ) internal { uint16 offset = 0; while (offset < supplies.length - numNFTs) { _mintBatch(offset, supplies, owner, ids); offset += 8; } // deal with NFT last. they do not care of balance packing if (numNFTs > 0) { _mintNFTs(uint16(supplies.length - numNFTs), numNFTs, owner, ids); } } function _mintNFTs( uint16 offset, uint32 numNFTs, address owner, uint256[] memory ids ) internal { for (uint16 i = 0; i < numNFTs; i++) { uint256 id = ids[i + offset]; _owners[id] = uint256(owner); emit Transfer(address(0), owner, id); } _numNFTPerAddress[owner] += numNFTs; } function _mintBatch( uint16 offset, uint256[] memory supplies, address owner, uint256[] memory ids ) internal { uint256 firstId = ids[offset]; (uint256 bin, uint256 index) = firstId.getTokenBinIndex(); uint256 balances = _packedTokenBalance[owner][bin]; for (uint256 i = 0; i < 8 && offset + i < supplies.length; i++) { uint256 j = offset + i; if (supplies[j] > 1) { balances = balances.updateTokenBalance(index + i, supplies[j], ObjectLib32.Operations.REPLACE); } else { break; } } _packedTokenBalance[owner][bin] = balances; } function _transferFrom( address from, address to, uint256 id, uint256 value ) internal returns (bool metaTx) { require(to != address(0), "destination is zero address"); require(from != address(0), "from is zero address"); metaTx = _metaTransactionContracts[msg.sender]; bool authorized = from == msg.sender || metaTx || _superOperators[msg.sender] || _operatorsForAll[from][msg.sender]; if (id & IS_NFT > 0) { require(authorized || _erc721operators[id] == msg.sender, "Operator not approved"); if (value > 0) { require(value == 1, "cannot transfer nft if amount not 1"); _numNFTPerAddress[from]--; _numNFTPerAddress[to]++; _owners[id] = uint256(to); if (_erc721operators[id] != address(0)) { // TODO operatorEnabled flag optimization (like in ERC721BaseToken) _erc721operators[id] = address(0); } emit Transfer(from, to, id); } } else { require(authorized, "Operator not approved"); if (value > 0) { // if different owners it will fails (uint256 bin, uint256 index) = id.getTokenBinIndex(); _packedTokenBalance[from][bin] = _packedTokenBalance[from][bin].updateTokenBalance( index, value, ObjectLib32.Operations.SUB ); _packedTokenBalance[to][bin] = _packedTokenBalance[to][bin].updateTokenBalance( index, value, ObjectLib32.Operations.ADD ); } } emit TransferSingle(metaTx ? from : msg.sender, from, to, id, value); } /// @notice Transfers `value` tokens of type `id` from `from` to `to` (with safety call). /// @param from address from which tokens are transfered. /// @param to address to which the token will be transfered. /// @param id the token type transfered. /// @param value amount of token transfered. /// @param data aditional data accompanying the transfer. function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes calldata data ) external { if (id & IS_NFT > 0) { require(_ownerOf(id) == from, "not owner"); } bool metaTx = _transferFrom(from, to, id, value); require( _checkERC1155AndCallSafeTransfer(metaTx ? from : msg.sender, from, to, id, value, data, false, false), "erc1155 transfer rejected" ); } /// @notice Transfers `values` tokens of type `ids` from `from` to `to` (with safety call). /// @dev call data should be optimized to order ids so packedBalance can be used efficiently. /// @param from address from which tokens are transfered. /// @param to address to which the token will be transfered. /// @param ids ids of each token type transfered. /// @param values amount of each token type transfered. /// @param data aditional data accompanying the transfer. function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external { require(ids.length == values.length, "Inconsistent array length between args"); require(to != address(0), "destination is zero address"); require(from != address(0), "from is zero address"); bool metaTx = _metaTransactionContracts[msg.sender]; bool authorized = from == msg.sender || metaTx || _superOperators[msg.sender] || _operatorsForAll[from][msg.sender]; // solium-disable-line max-len _batchTransferFrom(from, to, ids, values, authorized); emit TransferBatch(metaTx ? from : msg.sender, from, to, ids, values); require( _checkERC1155AndCallSafeBatchTransfer(metaTx ? from : msg.sender, from, to, ids, values, data), "erc1155 transfer rejected" ); } function _batchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory values, bool authorized ) internal { uint256 numItems = ids.length; uint256 bin; uint256 index; uint256 balFrom; uint256 balTo; uint256 lastBin; uint256 numNFTs = 0; for (uint256 i = 0; i < numItems; i++) { if (ids[i] & IS_NFT > 0) { require(authorized || _erc721operators[ids[i]] == msg.sender, "Operator not approved"); if (values[i] > 0) { require(values[i] == 1, "cannot transfer nft if amount not 1"); require(_ownerOf(ids[i]) == from, "not owner"); numNFTs++; _owners[ids[i]] = uint256(to); if (_erc721operators[ids[i]] != address(0)) { // TODO operatorEnabled flag optimization (like in ERC721BaseToken) _erc721operators[ids[i]] = address(0); } emit Transfer(from, to, ids[i]); } } else { require(authorized, "Operator not approved"); if (from == to) { _checkEnoughBalance(from, ids[i], values[i]); } else if (values[i] > 0) { (bin, index) = ids[i].getTokenBinIndex(); if (lastBin == 0) { lastBin = bin; balFrom = ObjectLib32.updateTokenBalance( _packedTokenBalance[from][bin], index, values[i], ObjectLib32.Operations.SUB ); balTo = ObjectLib32.updateTokenBalance( _packedTokenBalance[to][bin], index, values[i], ObjectLib32.Operations.ADD ); } else { if (bin != lastBin) { _packedTokenBalance[from][lastBin] = balFrom; _packedTokenBalance[to][lastBin] = balTo; balFrom = _packedTokenBalance[from][bin]; balTo = _packedTokenBalance[to][bin]; lastBin = bin; } balFrom = balFrom.updateTokenBalance(index, values[i], ObjectLib32.Operations.SUB); balTo = balTo.updateTokenBalance(index, values[i], ObjectLib32.Operations.ADD); } } } } if (numNFTs > 0 && from != to) { _numNFTPerAddress[from] -= numNFTs; _numNFTPerAddress[to] += numNFTs; } if (bin != 0 && from != to) { _packedTokenBalance[from][bin] = balFrom; _packedTokenBalance[to][bin] = balTo; } } function _checkEnoughBalance( address from, uint256 id, uint256 value ) internal { (uint256 bin, uint256 index) = id.getTokenBinIndex(); require(_packedTokenBalance[from][bin].getValueInBin(index) >= value, "can't substract more than there is"); } /// @notice Get the balance of `owner` for the token type `id`. /// @param owner The address of the token holder. /// @param id the token type of which to get the balance of. /// @return the balance of `owner` for the token type `id`. function balanceOf(address owner, uint256 id) public view returns (uint256) { // do not check for existence, balance is zero if never minted // require(wasEverMinted(id), "token was never minted"); if (id & IS_NFT > 0) { if (_ownerOf(id) == owner) { return 1; } else { return 0; } } (uint256 bin, uint256 index) = id.getTokenBinIndex(); return _packedTokenBalance[owner][bin].getValueInBin(index); } /// @notice Get the balance of `owners` for each token type `ids`. /// @param owners the addresses of the token holders queried. /// @param ids ids of each token type to query. /// @return the balance of each `owners` for each token type `ids`. function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view returns (uint256[] memory) { require(owners.length == ids.length, "Inconsistent array length between args"); uint256[] memory balances = new uint256[](ids.length); for (uint256 i = 0; i < ids.length; i++) { balances[i] = balanceOf(owners[i], ids[i]); } return balances; } /// @notice Get the creator of the token type `id`. /// @param id the id of the token to get the creator of. /// @return the creator of the token type `id`. function creatorOf(uint256 id) external view returns (address) { require(wasEverMinted(id), "token was never minted"); address originalCreator = address(id / CREATOR_OFFSET_MULTIPLIER); address newCreator = _creatorship[originalCreator]; if (newCreator != address(0)) { return newCreator; } return originalCreator; } /// @notice Transfers creatorship of `original` from `sender` to `to`. /// @param sender address of current registered creator. /// @param original address of the original creator whose creation are saved in the ids themselves. /// @param to address which will be given creatorship for all tokens originally minted by `original`. function transferCreatorship( address sender, address original, address to ) external { require( msg.sender == sender || _metaTransactionContracts[msg.sender] || _superOperators[msg.sender], "require meta approval" ); require(sender != address(0), "sender is zero address"); require(to != address(0), "destination is zero address"); address current = _creatorship[original]; if (current == address(0)) { current = original; } require(current != to, "current == to"); require(current == sender, "current != sender"); if (to == original) { _creatorship[original] = address(0); } else { _creatorship[original] = to; } emit CreatorshipTransfer(original, current, to); } /// @notice Enable or disable approval for `operator` to manage all `sender`'s tokens. /// @dev used for Meta Transaction (from metaTransactionContract). /// @param sender address which grant approval. /// @param operator address which will be granted rights to transfer all token owned by `sender`. /// @param approved whether to approve or revoke. function setApprovalForAllFor( address sender, address operator, bool approved ) external { require( msg.sender == sender || _metaTransactionContracts[msg.sender] || _superOperators[msg.sender], "require meta approval" ); _setApprovalForAll(sender, operator, approved); } /// @notice Enable or disable approval for `operator` to manage all of the caller's tokens. /// @param operator address which will be granted rights to transfer all tokens of the caller. /// @param approved whether to approve or revoke function setApprovalForAll(address operator, bool approved) external { _setApprovalForAll(msg.sender, operator, approved); } function _setApprovalForAll( address sender, address operator, bool approved ) internal { require(sender != address(0), "sender is zero address"); require(sender != operator, "sender = operator"); require(operator != address(0), "operator is zero address"); require(!_superOperators[operator], "super operator can't have their approvalForAll changed"); _operatorsForAll[sender][operator] = approved; emit ApprovalForAll(sender, operator, approved); } /// @notice Queries the approval status of `operator` for owner `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 isOperator) { require(owner != address(0), "owner is zero address"); require(operator != address(0), "operator is zero address"); return _operatorsForAll[owner][operator] || _superOperators[operator]; } /// @notice Count all NFTs assigned to `owner`. /// @param owner 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 balance) { require(owner != address(0), "owner is zero address"); return _numNFTPerAddress[owner]; } /// @notice Find the owner of an NFT. /// @param id the identifier for an NFT. /// @return the address of the owner of the NFT. function ownerOf(uint256 id) external view returns (address owner) { owner = _ownerOf(id); require(owner != address(0), "NFT does not exist"); } function _ownerOf(uint256 id) internal view returns (address) { return address(_owners[id]); } /// @notice Change or reaffirm the approved address for an NFT for `sender`. /// @dev used for Meta Transaction (from metaTransactionContract). /// @param sender the sender granting control. /// @param operator the address to approve as NFT controller. /// @param id the NFT to approve. function approveFor( address sender, address operator, uint256 id ) external { address owner = _ownerOf(id); require(sender != address(0), "sender is zero address"); require( msg.sender == sender || _metaTransactionContracts[msg.sender] || _superOperators[msg.sender] || _operatorsForAll[sender][msg.sender], "require operators" ); // solium-disable-line max-len require(owner == sender, "not owner"); _erc721operators[id] = operator; emit Approval(owner, operator, id); } /// @notice Change or reaffirm the approved address for an NFT. /// @param operator the address to approve as NFT controller. /// @param id the id of the NFT to approve. function approve(address operator, uint256 id) external { address owner = _ownerOf(id); require(owner != address(0), "NFT does not exist"); require( owner == msg.sender || _superOperators[msg.sender] || _operatorsForAll[owner][msg.sender], "not authorized" ); _erc721operators[id] = operator; emit Approval(owner, operator, id); } /// @notice Get the approved address for a single NFT. /// @param id 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 id) external view returns (address operator) { require(_ownerOf(id) != address(0), "NFT does not exist"); return _erc721operators[id]; } /// @notice Transfers ownership of an NFT. /// @param from the current owner of the NFT. /// @param to the new owner. /// @param id the NFT to transfer. function transferFrom( address from, address to, uint256 id ) external { require(_ownerOf(id) == from, "not owner"); bool metaTx = _transferFrom(from, to, id, 1); require( _checkERC1155AndCallSafeTransfer(metaTx ? from : msg.sender, from, to, id, 1, "", true, false), "erc1155 transfer rejected" ); } /// @notice Transfers the ownership of an NFT from one address to another address. /// @param from the current owner of the NFT. /// @param to the new owner. /// @param id the NFT to transfer. function safeTransferFrom( address from, address to, uint256 id ) external { safeTransferFrom(from, to, id, ""); } /// @notice Transfers the ownership of an NFT from one address to another address. /// @param from the current owner of the NFT. /// @param to the new owner. /// @param id the NFT to transfer. /// @param data additional data with no specified format, sent in call to `to`. function safeTransferFrom( address from, address to, uint256 id, bytes memory data ) public { require(_ownerOf(id) == from, "not owner"); bool metaTx = _transferFrom(from, to, id, 1); require( _checkERC1155AndCallSafeTransfer(metaTx ? from : msg.sender, from, to, id, 1, data, true, true), "erc721/erc1155 transfer rejected" ); } /// @notice A descriptive name for the collection of tokens in this contract. /// @return the name of the tokens. function name() external pure returns (string memory _name) { return "Wonderland's ASSETs"; } /// @notice An abbreviated name for the collection of tokens in this contract. /// @return the symbol of the tokens. function symbol() external pure returns (string memory _symbol) { return "ASSET"; } /// @notice Gives the rarity power of a particular token type. /// @param id the token type to get the rarity of. /// @return the rarity power(between 0 and 3). function rarity(uint256 id) public view returns (uint256) { require(wasEverMinted(id), "token was never minted"); bytes storage rarityPack = _rarityPacks[id & URI_ID]; uint256 packIndex = id & PACK_INDEX; if (packIndex / 4 >= rarityPack.length) { return 0; } else { uint8 pack = uint8(rarityPack[packIndex / 4]); uint8 i = (3 - uint8(packIndex % 4)) * 2; return (pack / (uint8(2)**i)) % 4; } } /// @notice Gives the collection a specific token belongs to. /// @param id the token to get the collection of. /// @return the collection the NFT is part of. function collectionOf(uint256 id) public view returns (uint256) { require(_ownerOf(id) != address(0), "NFT does not exist"); uint256 collectionId = id & NOT_NFT_INDEX & NOT_IS_NFT; require(wasEverMinted(collectionId), "no collection ever minted for that token"); return collectionId; } /// @notice Return wether the id is a collection /// @param id collectionId to check. /// @return whether the id is a collection. function isCollection(uint256 id) public view returns (bool) { uint256 collectionId = id & NOT_NFT_INDEX & NOT_IS_NFT; return wasEverMinted(collectionId); } /// @notice Gives the index at which an NFT was minted in a collection : first of a collection get the zero index. /// @param id the token to get the index of. /// @return the index/order at which the token `id` was minted in a collection. function collectionIndexOf(uint256 id) public view returns (uint256) { collectionOf(id); // this check if id and collection indeed was ever minted return uint32((id & NFT_INDEX) >> NFT_INDEX_OFFSET); } function toFullURI(bytes32 hash, uint256 id) internal pure returns (string memory) { return string(abi.encodePacked("ipfs://bafybei", hash2base32(hash), "/", uint2str(id & PACK_INDEX), ".json")); } function wasEverMinted(uint256 id) public view returns (bool) { if ((id & IS_NFT) > 0) { return _owners[id] != 0; } else { return ((id & PACK_INDEX) < ((id & PACK_NUM_FT_TYPES) / PACK_NUM_FT_TYPES_OFFSET_MULTIPLIER)) && _metadataHash[id & URI_ID] != 0; } } /// @notice check whether a packId/numFT tupple has been used /// @param creator for which creator /// @param packId the packId to check /// @param numFTs number of Fungible Token in that pack (can reuse packId if different) /// @return whether the pack has already been used function isPackIdUsed( address creator, uint40 packId, uint16 numFTs ) external returns (bool) { uint256 uriId = uint256(creator) * CREATOR_OFFSET_MULTIPLIER + // CREATOR uint256(packId) * PACK_ID_OFFSET_MULTIPLIER + // packId (unique pack) // PACk_ID numFTs * PACK_NUM_FT_TYPES_OFFSET_MULTIPLIER; // number of fungible token in the pack // PACK_NUM_FT_TYPES return _metadataHash[uriId] != 0; } /// @notice A distinct Uniform Resource Identifier (URI) for a given token. /// @param id token to get the uri of. /// @return URI string function uri(uint256 id) public view returns (string memory) { require(wasEverMinted(id), "token was never minted"); // prevent returning invalid uri return toFullURI(_metadataHash[id & URI_ID], id); } /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @param id token to get the uri of. /// @return URI string function tokenURI(uint256 id) public view returns (string memory) { require(_ownerOf(id) != address(0), "NFT does not exist"); return toFullURI(_metadataHash[id & URI_ID], id); } bytes32 private constant base32Alphabet = 0x6162636465666768696A6B6C6D6E6F707172737475767778797A323334353637; // solium-disable-next-line security/no-assign-params function hash2base32(bytes32 hash) private pure returns (string memory _uintAsString) { uint256 _i = uint256(hash); uint256 k = 52; bytes memory bstr = new bytes(k); bstr[--k] = base32Alphabet[uint8((_i % 8) << 2)]; // uint8 s = uint8((256 - skip) % 5); // (_i % (2**s)) << (5-s) _i /= 8; while (k > 0) { bstr[--k] = base32Alphabet[_i % 32]; _i /= 32; } return string(bstr); } // solium-disable-next-line security/no-assign-params function uint2str(uint256 _i) private pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); } /// @notice Query if a contract implements interface `id`. /// @param id the interface identifier, as specified in ERC-165. /// @return `true` if the contract implements `id`. function supportsInterface(bytes4 id) external view returns (bool) { return id == 0x01ffc9a7 || //ERC165 id == 0xd9b67a26 || // ERC1155 id == 0x80ac58cd || // ERC721 id == 0x5b5e139f || // ERC721 metadata id == 0x0e89341c; // ERC1155 metadata } bytes4 constant ERC165ID = 0x01ffc9a7; function checkIsERC1155Receiver(address _contract) internal view returns (bool) { bool success; bool result; bytes memory call_data = abi.encodeWithSelector(ERC165ID, ERC1155_IS_RECEIVER); // solium-disable-next-line security/no-inline-assembly assembly { let call_ptr := add(0x20, call_data) let call_size := mload(call_data) let output := mload(0x40) // Find empty storage location using "free memory pointer" mstore(output, 0x0) success := staticcall(10000, _contract, call_ptr, call_size, output, 0x20) // 32 bytes result := mload(output) } // (10000 / 63) "not enough for supportsInterface(...)" // consume all gas, so caller can potentially know that there was not enough gas assert(gasleft() > 158); return success && result; } function _checkERC1155AndCallSafeTransfer( address operator, address from, address to, uint256 id, uint256 value, bytes memory data, bool erc721, bool erc721Safe ) internal returns (bool) { if (!to.isContract()) { return true; } if (erc721) { if (!checkIsERC1155Receiver(to)) { if (erc721Safe) { return _checkERC721AndCallSafeTransfer(operator, from, to, id, data); } else { return true; } } } return ERC1155TokenReceiver(to).onERC1155Received(operator, from, id, value, data) == ERC1155_RECEIVED; } function _checkERC1155AndCallSafeBatchTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = ERC1155TokenReceiver(to).onERC1155BatchReceived(operator, from, ids, values, data); return (retval == ERC1155_BATCH_RECEIVED); } function _checkERC721AndCallSafeTransfer( address operator, address from, address to, uint256 id, bytes memory data ) internal returns (bool) { // following not required as this function is always called as part of ERC1155 checks that include such check already // if (!to.isContract()) { // return true; // } return (ERC721TokenReceiver(to).onERC721Received(operator, from, id, data) == ERC721_RECEIVED); } event Extraction(uint256 indexed fromId, uint256 toId); event AssetUpdate(uint256 indexed fromId, uint256 toId); function _burnERC1155( address operator, address from, uint256 id, uint32 amount ) internal { (uint256 bin, uint256 index) = (id).getTokenBinIndex(); _packedTokenBalance[from][bin] = _packedTokenBalance[from][bin].updateTokenBalance( index, amount, ObjectLib32.Operations.SUB ); emit TransferSingle(operator, from, address(0), id, amount); } function _burnERC721( address operator, address from, uint256 id ) internal { require(from == _ownerOf(id), "not owner"); _owners[id] = 2**160; // equivalent to zero address when casted but ensure we track minted status _numNFTPerAddress[from]--; emit Transfer(from, address(0), id); emit TransferSingle(operator, from, address(0), id, 1); } /// @notice Burns `amount` tokens of type `id`. /// @param id token type which will be burnt. /// @param amount amount of token to burn. function burn(uint256 id, uint256 amount) external { _burn(msg.sender, id, amount); } /// @notice Burns `amount` tokens of type `id` from `from`. /// @param from address whose token is to be burnt. /// @param id token type which will be burnt. /// @param amount amount of token to burn. function burnFrom( address from, uint256 id, uint256 amount ) external { require(from != address(0), "from is zero address"); require( msg.sender == from || _metaTransactionContracts[msg.sender] || _superOperators[msg.sender] || _operatorsForAll[from][msg.sender], "require meta approval" ); _burn(from, id, amount); } function _burn( address from, uint256 id, uint256 amount ) internal { if ((id & IS_NFT) > 0) { require(amount == 1, "can only burn one NFT"); _burnERC721(_metaTransactionContracts[msg.sender] ? from : msg.sender, from, id); } else { require(amount > 0 && amount <= MAX_SUPPLY, "invalid amount"); _burnERC1155(_metaTransactionContracts[msg.sender] ? from : msg.sender, from, id, uint32(amount)); } } /// @notice Upgrades an NFT with new metadata and rarity. /// @param from address which own the NFT to be upgraded. /// @param id the NFT that will be burnt to be upgraded. /// @param packId unqiue packId for the token. /// @param hash hash of an IPFS cidv1 folder that contains the metadata of the new token type in the file 0.json. /// @param newRarity rarity power of the new NFT. /// @param to address which will receive the NFT. /// @param data bytes to be transmitted as part of the minted token. /// @return the id of the newly minted NFT. function updateERC721( address from, uint256 id, uint40 packId, bytes32 hash, uint8 newRarity, address to, bytes calldata data ) external returns (uint256) { require(hash != 0, "hash is zero"); require(_bouncers[msg.sender], "only bouncer allowed to mint via update"); require(to != address(0), "destination is zero address"); require(from != address(0), "from is zero address"); _burnERC721(msg.sender, from, id); uint256 newId = generateTokenId(from, 1, packId, 0, 0); _mint(hash, 1, newRarity, msg.sender, to, newId, data, false); emit AssetUpdate(id, newId); return newId; } /// @notice Extracts an EIP-721 NFT from an EIP-1155 token. /// @param id the token type to extract from. /// @param to address which will receive the token. /// @return the id of the newly minted NFT. function extractERC721(uint256 id, address to) external returns (uint256 newId) { return _extractERC721From(msg.sender, msg.sender, id, to); } /// @notice Extracts an EIP-721 NFT from an EIP-1155 token. /// @param sender address which own the token to be extracted. /// @param id the token type to extract from. /// @param to address which will receive the token. /// @return the id of the newly minted NFT. function extractERC721From( address sender, uint256 id, address to ) external returns (uint256 newId) { bool metaTx = _metaTransactionContracts[msg.sender]; require( msg.sender == sender || metaTx || _superOperators[msg.sender] || _operatorsForAll[sender][msg.sender], "require meta approval" ); return _extractERC721From(metaTx ? sender : msg.sender, sender, id, to); } function _extractERC721From( address operator, address sender, uint256 id, address to ) internal returns (uint256 newId) { require(to != address(0), "destination is zero address"); require(id & IS_NFT == 0, "Not an ERC1155 Token"); uint32 tokenCollectionIndex = _nextCollectionIndex[id]; newId = id + IS_NFT + (tokenCollectionIndex) * 2**NFT_INDEX_OFFSET; _nextCollectionIndex[id] = tokenCollectionIndex + 1; _burnERC1155(operator, sender, id, 1); _mint(_metadataHash[id & URI_ID], 1, 0, operator, to, newId, "", true); emit Extraction(id, newId); } } pragma solidity ^0.5.2; /** @title ERC-1155 Multi Token Standard @dev See https://eips.ethereum.org/EIPS/eip-1155 Note: The ERC-165 identifier for this interface is 0xd9b67a26. */ interface ERC1155 { event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); event URI(string value, uint256 indexed id); /** @notice Transfers `value` amount of an `id` from `from` to `to` (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `from` account (see "Approval" section of the standard). MUST revert if `to` is the zero address. MUST revert if balance of holder for token `id` is lower than the `value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `to` and act appropriately (see "Safe Transfer Rules" section of the standard). @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, MUST be sent unaltered in call to `onERC1155Received` on `to` */ function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes calldata data ) external; /** @notice Transfers `values` amount(s) of `ids` from the `from` address to the `to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `from` account (see "Approval" section of the standard). MUST revert if `to` is the zero address. MUST revert if length of `ids` is not the same as length of `values`. MUST revert if any of the balance(s) of the holder(s) for token(s) in `ids` is lower than the respective amount(s) in `values` sent to the recipient. MUST revert on any other error. MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). After the above conditions for the transfer(s) in the batch are met, this function MUST check if `to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param from Source address @param to Target address @param ids IDs of each token type (order and length must match _values array) @param values Transfer amounts per token type (order and length must match _ids array) @param data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `to` */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; /** @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 The _owner's balance of the token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view returns (uint256[] memory); /** @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); } pragma solidity ^0.5.2; /** Note: The ERC-165 identifier for this interface is 0x4e2312e0. */ interface ERC1155TokenReceiver { /** @notice Handle the receipt of a single ERC1155 token type. @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated. This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer. This function MUST revert if it rejects the transfer. Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value 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 An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated. This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s). This function MUST revert if it rejects the transfer(s). Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match _values array) @param values An array containing amounts of each token being transferred (order and length must match _ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(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.5.2; library AddressUtils { function toPayable(address _address) internal pure returns (address payable _payable) { return address(uint160(_address)); } function isContract(address addr) internal view returns (bool) { // for accounts without code, i.e. `keccak256('')`: bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; bytes32 codehash; // solium-disable-next-line security/no-inline-assembly assembly { codehash := extcodehash(addr) } return (codehash != 0x0 && codehash != accountHash); } } pragma solidity ^0.5.2; import "./SafeMathWithRequire.sol"; library ObjectLib32 { using SafeMathWithRequire for uint256; enum Operations {ADD, SUB, REPLACE} // Constants regarding bin or chunk sizes for balance packing uint256 constant TYPES_BITS_SIZE = 32; // Max size of each object uint256 constant TYPES_PER_UINT256 = 256 / TYPES_BITS_SIZE; // Number of types per uint256 // // Objects and Tokens Functions // /** * @dev Return the bin number and index within that bin where ID is * @param tokenId Object type * @return (Bin number, ID's index within that bin) */ function getTokenBinIndex(uint256 tokenId) internal pure returns (uint256 bin, uint256 index) { bin = (tokenId * TYPES_BITS_SIZE) / 256; index = tokenId % TYPES_PER_UINT256; return (bin, index); } /** * @dev update the balance of a type provided in binBalances * @param binBalances Uint256 containing the balances of objects * @param index Index of the object in the provided bin * @param amount Value to update the type balance * @param operation Which operation to conduct : * Operations.REPLACE : Replace type balance with amount * Operations.ADD : ADD amount to type balance * Operations.SUB : Substract amount from type balance */ function updateTokenBalance( uint256 binBalances, uint256 index, uint256 amount, Operations operation ) internal pure returns (uint256 newBinBalance) { uint256 objectBalance = 0; if (operation == Operations.ADD) { objectBalance = getValueInBin(binBalances, index); newBinBalance = writeValueInBin( binBalances, index, objectBalance.add(amount) ); } else if (operation == Operations.SUB) { objectBalance = getValueInBin(binBalances, index); require(objectBalance >= amount, "can't substract more than there is"); newBinBalance = writeValueInBin( binBalances, index, objectBalance.sub(amount) ); } else if (operation == Operations.REPLACE) { newBinBalance = writeValueInBin(binBalances, index, amount); } else { revert("Invalid operation"); // Bad operation } return newBinBalance; } /* * @dev return value in binValue at position index * @param binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param index index at which to retrieve value * @return Value at given index in bin */ function getValueInBin(uint256 binValue, uint256 index) internal pure returns (uint256) { // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 rightShift = 256 - TYPES_BITS_SIZE * (index + 1); return (binValue >> rightShift) & mask; } /** * @dev return the updated binValue after writing amount at index * @param binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param index Index at which to retrieve value * @param amount Value to store at index in bin * @return Value at given index in bin */ function writeValueInBin(uint256 binValue, uint256 index, uint256 amount) internal pure returns (uint256) { require( amount < 2**TYPES_BITS_SIZE, "Amount to write in bin is too large" ); // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 leftShift = 256 - TYPES_BITS_SIZE * (index + 1); return (binValue & ~(mask << leftShift)) | (amount << leftShift); } } pragma solidity ^0.5.2; import "./ERC165.sol"; import "./ERC721Events.sol"; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://eips.ethereum.org/EIPS/eip-721 */ /*interface*/ contract ERC721 is ERC165, ERC721Events { function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); // function exists(uint256 tokenId) external view returns (bool exists); function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function transferFrom(address from, address to, uint256 tokenId) external; function safeTransferFrom(address from, address to, uint256 tokenId) external; function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed pragma solidity ^0.5.2; interface ERC721TokenReceiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } pragma solidity ^0.5.2; import "./Admin.sol"; contract SuperOperators is Admin { mapping(address => bool) internal _superOperators; event SuperOperator(address superOperator, bool enabled); /// @notice Enable or disable the ability of `superOperator` to transfer tokens of all (superOperator rights). /// @param superOperator address that will be given/removed superOperator right. /// @param enabled set whether the superOperator is enabled or disabled. function setSuperOperator(address superOperator, bool enabled) external { require( msg.sender == _admin, "only admin is allowed to add super operators" ); _superOperators[superOperator] = enabled; emit SuperOperator(superOperator, enabled); } /// @notice check whether address `who` is given superOperator rights. /// @param who The address to query. /// @return whether the address has superOperator rights. function isSuperOperator(address who) public view returns (bool) { return _superOperators[who]; } } pragma solidity ^0.5.2; /** * @title SafeMath * @dev Math operations with safety checks that revert */ library SafeMathWithRequire { /** * @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; require(c / a == b, "overflow"); 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) { require(b <= a, "undeflow"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "overflow"); return c; } } pragma solidity ^0.5.2; /** * @title ERC165 * @dev https://eips.ethereum.org/EIPS/eip-165 */ interface ERC165 { /** * @notice Query if a contract implements interface `interfaceId` * @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. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } pragma solidity ^0.5.2; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://eips.ethereum.org/EIPS/eip-721 */ interface ERC721Events { event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); } pragma solidity ^0.5.2; contract Admin { address internal _admin; event AdminChanged(address oldAdmin, address newAdmin); /// @notice gives the current administrator of this contract. /// @return the current administrator of this contract. function getAdmin() external view returns (address) { return _admin; } /// @notice change the administrator to be `newAdmin`. /// @param newAdmin address of the new administrator. function changeAdmin(address newAdmin) external { require(msg.sender == _admin, "only admin can change admin"); emit AdminChanged(_admin, newAdmin); _admin = newAdmin; } modifier onlyAdmin() { require (msg.sender == _admin, "only admin allowed"); _; } }
Transfers ownership of an NFT. from the current owner of the NFT. to the new owner. id the NFT to transfer.
function transferFrom( address from, address to, uint256 id ) external { require(_ownerOf(id) == from, "not owner"); bool metaTx = _transferFrom(from, to, id, 1); require( _checkERC1155AndCallSafeTransfer(metaTx ? from : msg.sender, from, to, id, 1, "", true, false), "erc1155 transfer rejected" ); }
14,331,010
./full_match/11155111/0x04708D0457f3EFa5F15E305E72a94E4f2e8B5F2d/sources/_minteeble/smart-contracts/contracts/token/extensions/WhitelistExtension.sol
Allows owner to set the max number of mintable items per account _maxAmount Max amount/
function _setWhitelistMaxMintAmountPerAddress(uint256 _maxAmount) internal { maxWhitelistMintAmountPerAddress = _maxAmount; }
3,791,016
//Address: 0x51b3e8bc61e9c21e979468379d3147d6b955b79f //Contract name: UBOCOIN //Balance: 0 Ether //Verification Date: 2/5/2018 //Transacion Count: 20 // CODE STARTS HERE pragma solidity ^0.4.19; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // 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) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { 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 { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event 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; } } contract UBOCOIN is BurnableToken, Ownable { // ERC20 token parameters string public constant name = "UBOCOIN"; string public constant symbol = "UBO"; uint8 public constant decimals = 18; // Crowdsale base price (before bonuses): 0.001 ETH per UBO uint256 private UBO_per_ETH = 1000 * (uint256(10) ** decimals); // 14 days with 43% bonus for purchases of at least 1000 UBO (19 february - 5 march) uint256 private constant pre_ICO_duration = 15 days; uint256 private constant pre_ICO_bonus_percentage = 43; uint256 private constant pre_ICO_bonus_minimum_purchased_UBO = 1000 * (uint256(10) ** decimals); // 21 days with 15% bonus (6 march - 26 march) uint256 private constant first_bonus_sale_duration = 21 days; uint256 private constant first_bonus_sale_bonus = 15; // 15 days with 10% bonus (27 march - 10 april) uint256 private constant second_bonus_sale_duration = 15 days; uint256 private constant second_bonus_sale_bonus = 10; // 8 days with 6% bonus (11 april - 18 april) uint256 private constant third_bonus_sale_duration = 8 days; uint256 private constant third_bonus_sale_bonus = 6; // 7 days with 3% bonus (19 april - 25 april) uint256 private constant fourth_bonus_sale_duration = 7 days; uint256 private constant fourth_bonus_sale_bonus = 3; // 5 days with no bonus (26 april - 30 april) uint256 private constant final_sale_duration = 5 days; // The target of the crowdsale is 3500000 UBICOINS. // If the crowdsale has finished, and the target has not been reached, // all crowdsale participants will be able to call refund() and get their // ETH back. The refundMany() function can be used to refund multiple // participants in one transaction. uint256 public constant crowdsaleTargetUBO = 3500000 * (uint256(10) ** decimals); // Variables that remember the start times of the various crowdsale periods uint256 private pre_ICO_start_timestamp; uint256 private first_bonus_sale_start_timestamp; uint256 private second_bonus_sale_start_timestamp; uint256 private third_bonus_sale_start_timestamp; uint256 private fourth_bonus_sale_start_timestamp; uint256 private final_sale_start_timestamp; uint256 private crowdsale_end_timestamp; // Publicly accessible trackers that indicate how much UBO is left // in each category uint256 public crowdsaleAmountLeft; uint256 public foundersAmountLeft; uint256 public earlyBackersAmountLeft; uint256 public teamAmountLeft; uint256 public bountyAmountLeft; uint256 public reservedFundLeft; // Keep track of all participants, how much they bought and how much they spent. address[] public allParticipants; mapping(address => uint256) public participantToEtherSpent; mapping(address => uint256) public participantToUBObought; function crowdsaleTargetReached() public view returns (bool) { return amountOfUBOsold() >= crowdsaleTargetUBO; } function crowdsaleStarted() public view returns (bool) { return pre_ICO_start_timestamp > 0 && now >= pre_ICO_start_timestamp; } function crowdsaleFinished() public view returns (bool) { return pre_ICO_start_timestamp > 0 && now >= crowdsale_end_timestamp; } function amountOfParticipants() external view returns (uint256) { return allParticipants.length; } function amountOfUBOsold() public view returns (uint256) { return totalSupply_ * 70 / 100 - crowdsaleAmountLeft; } // If the crowdsale target has not been reached, or the crowdsale has not finished, // don't allow the transfer of tokens purchased in the crowdsale. function transfer(address _to, uint256 _amount) public returns (bool) { if (!crowdsaleTargetReached() || !crowdsaleFinished()) { require(balances[msg.sender] - participantToUBObought[msg.sender] >= _amount); } return super.transfer(_to, _amount); } // Constructor function function UBOCOIN() public { totalSupply_ = 300000000 * (uint256(10) ** decimals); balances[this] = totalSupply_; Transfer(0x0, this, totalSupply_); crowdsaleAmountLeft = totalSupply_ * 70 / 100; // 70% foundersAmountLeft = totalSupply_ * 10 / 100; // 10% earlyBackersAmountLeft = totalSupply_ * 5 / 100; // 5% teamAmountLeft = totalSupply_ * 5 / 100; // 5% bountyAmountLeft = totalSupply_ * 5 / 100; // 5% reservedFundLeft = totalSupply_ * 5 / 100; // 5% setPreICOStartTime(1518998400); // This timstamp indicates 2018-02-19 00:00 UTC } function setPreICOStartTime(uint256 _timestamp) public onlyOwner { // If the crowdsale has already started, don't allow re-scheduling it. require(!crowdsaleStarted()); pre_ICO_start_timestamp = _timestamp; first_bonus_sale_start_timestamp = pre_ICO_start_timestamp + pre_ICO_duration; second_bonus_sale_start_timestamp = first_bonus_sale_start_timestamp + first_bonus_sale_duration; third_bonus_sale_start_timestamp = second_bonus_sale_start_timestamp + second_bonus_sale_duration; fourth_bonus_sale_start_timestamp = third_bonus_sale_start_timestamp + third_bonus_sale_duration; final_sale_start_timestamp = fourth_bonus_sale_start_timestamp + fourth_bonus_sale_duration; crowdsale_end_timestamp = final_sale_start_timestamp + final_sale_duration; } function startPreICOnow() external onlyOwner { setPreICOStartTime(now); } function destroyUnsoldTokens() external { require(crowdsaleStarted() && crowdsaleFinished()); uint256 amountToBurn = crowdsaleAmountLeft; crowdsaleAmountLeft = 0; this.burn(amountToBurn); } // If someone sends ETH to the contract address, // assume that they are trying to buy tokens. function () payable external { buyTokens(); } function buyTokens() payable public { uint256 amountOfUBOpurchased = msg.value * UBO_per_ETH / (1 ether); // Only allow buying tokens if the ICO has started, and has not finished require(crowdsaleStarted()); require(!crowdsaleFinished()); // If the pre-ICO hasn't started yet, cancel the transaction if (now < pre_ICO_start_timestamp) { revert(); } // If we are in the pre-ICO... else if (now >= pre_ICO_start_timestamp && now < first_bonus_sale_start_timestamp) { // If they purchased enough to be eligible for the pre-ICO bonus, // then give them the bonus if (amountOfUBOpurchased >= pre_ICO_bonus_minimum_purchased_UBO) { amountOfUBOpurchased = amountOfUBOpurchased * (100 + pre_ICO_bonus_percentage) / 100; } } // If we are in the first bonus sale... else if (now >= first_bonus_sale_start_timestamp && now < second_bonus_sale_start_timestamp) { amountOfUBOpurchased = amountOfUBOpurchased * (100 + first_bonus_sale_bonus) / 100; } // If we are in the second bonus sale... else if (now >= second_bonus_sale_start_timestamp && now < third_bonus_sale_start_timestamp) { amountOfUBOpurchased = amountOfUBOpurchased * (100 + second_bonus_sale_bonus) / 100; } // If we are in the third bonus sale... else if (now >= third_bonus_sale_start_timestamp && now < fourth_bonus_sale_start_timestamp) { amountOfUBOpurchased = amountOfUBOpurchased * (100 + third_bonus_sale_bonus) / 100; } // If we are in the fourth bonus sale... else if (now >= fourth_bonus_sale_start_timestamp && now < final_sale_start_timestamp) { amountOfUBOpurchased = amountOfUBOpurchased * (100 + fourth_bonus_sale_bonus) / 100; } // If we are in the final sale... else if (now >= final_sale_start_timestamp && now < crowdsale_end_timestamp) { // No bonus } // If we are passed the final sale, cancel the transaction. else { revert(); } // Make sure the crowdsale has enough UBO left require(amountOfUBOpurchased <= crowdsaleAmountLeft); // Remove the tokens from this contract and the crowdsale tokens, // add them to the buyer crowdsaleAmountLeft -= amountOfUBOpurchased; balances[this] -= amountOfUBOpurchased; balances[msg.sender] += amountOfUBOpurchased; Transfer(this, msg.sender, amountOfUBOpurchased); // Track statistics if (participantToEtherSpent[msg.sender] == 0) { allParticipants.push(msg.sender); } participantToUBObought[msg.sender] += amountOfUBOpurchased; participantToEtherSpent[msg.sender] += msg.value; } function refund() external { // If the crowdsale has not started yet, don't allow refund require(crowdsaleStarted()); // If the crowdsale has not finished yet, don't allow refund require(crowdsaleFinished()); // If the target was reached, don't allow refund require(!crowdsaleTargetReached()); _refundParticipant(msg.sender); } function refundMany(uint256 _startIndex, uint256 _endIndex) external { // If the crowdsale has not started yet, don't allow refund require(crowdsaleStarted()); // If the crowdsale has not finished yet, don't allow refund require(crowdsaleFinished()); // If the target was reached, don't allow refund require(!crowdsaleTargetReached()); for (uint256 i=_startIndex; i<=_endIndex && i<allParticipants.length; i++) { _refundParticipant(allParticipants[i]); } } function _refundParticipant(address _participant) internal { if (participantToEtherSpent[_participant] > 0) { // Return the UBO they bought into the crowdsale funds uint256 refundUBO = participantToUBObought[_participant]; participantToUBObought[_participant] = 0; balances[_participant] -= refundUBO; balances[this] += refundUBO; crowdsaleAmountLeft += refundUBO; Transfer(_participant, this, refundUBO); // Return the ETH they spent to buy them uint256 refundETH = participantToEtherSpent[_participant]; participantToEtherSpent[_participant] = 0; _participant.transfer(refundETH); } } function distributeFounderTokens(address _founderAddress, uint256 _amount) external onlyOwner { require(_amount <= foundersAmountLeft); foundersAmountLeft -= _amount; this.transfer(_founderAddress, _amount); } function distributeEarlyBackerTokens(address _earlyBackerAddress, uint256 _amount) external onlyOwner { require(_amount <= earlyBackersAmountLeft); earlyBackersAmountLeft -= _amount; this.transfer(_earlyBackerAddress, _amount); } function distributeTeamTokens(address _teamMemberAddress, uint256 _amount) external onlyOwner { require(_amount <= teamAmountLeft); teamAmountLeft -= _amount; this.transfer(_teamMemberAddress, _amount); } function distributeBountyTokens(address _bountyReceiverAddress, uint256 _amount) external onlyOwner { require(_amount <= bountyAmountLeft); bountyAmountLeft -= _amount; this.transfer(_bountyReceiverAddress, _amount); } function distributeReservedTokens(address _to, uint256 _amount) external onlyOwner { require(_amount <= reservedFundLeft); reservedFundLeft -= _amount; this.transfer(_to, _amount); } function distributeCrowdsaleTokens(address _to, uint256 _amount) external onlyOwner { require(_amount <= crowdsaleAmountLeft); crowdsaleAmountLeft -= _amount; this.transfer(_to, _amount); } function ownerWithdrawETH() external onlyOwner { // Only allow the owner to withdraw if the crowdsale target has been reached require(crowdsaleTargetReached()); owner.transfer(this.balance); } }
Return the UBO they bought into the crowdsale funds Return the ETH they spent to buy them
function _refundParticipant(address _participant) internal { if (participantToEtherSpent[_participant] > 0) { uint256 refundUBO = participantToUBObought[_participant]; participantToUBObought[_participant] = 0; balances[_participant] -= refundUBO; balances[this] += refundUBO; crowdsaleAmountLeft += refundUBO; Transfer(_participant, this, refundUBO); uint256 refundETH = participantToEtherSpent[_participant]; participantToEtherSpent[_participant] = 0; _participant.transfer(refundETH); } }
1,797,018
./full_match/5/0x77ba64C346E36E4b399af5bcEbbbDA35DB6b5019/sources/contracts/SuperPayroll.sol
deposits super tokens into contract approve contract to transfer tokens of employer
function depositAmount(uint256 _amount) public onlyEmployer { require( token.balanceOf(employer) >= _amount, "Not enough tokens to deposit" ); token.approve(address(this), _amount); token.transferFrom(employer, address(this), _amount); }
1,936,785
./partial_match/42/0xAD4932c1d9C9f2885089f3BED50A5Ae5e98b72B2/sources/InitialCashDistributor.sol
stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public override updateReward(msg.sender) checkStart { require(amount > 0, 'BACDAIPool: Cannot stake 0'); uint256 newDeposit = deposits[msg.sender].add(amount); require( newDeposit <= 20000e18, 'BACDAIPool: deposit amount exceeds maximum 20000' ); deposits[msg.sender] = newDeposit; super.stake(amount); emit Staked(msg.sender, amount); }
8,954,439
pragma solidity 0.4.19; /* An Ethereum version of recurring payments. Creator: 1. publishes address (via website, etc) 2. can withdraw a certain amount once every PERIOD Supporter: 1. Deposits ether 2. Pledges to give N wei to Creator once a PERIOD 3. Can unsubscribe any time (pledges for earlier periods not refunded) */ contract Pethreon { /***** EVENTS *****/ event SupporterDeposited(uint period, address supporter, uint amount); event PledgeCreated(uint period, address creator, address supporter, uint weiPerPeriod, uint periods); event PledgeCancelled(uint period, address creator, address supporter); event SupporterWithdrew(uint period, address supporter, uint amount); event CreatorWithdrew(uint period, address creator, uint amount); /***** CONSTANTS *****/ // Time is processed in steps of 1 PERIOD // Period 0 is the Start of epoch -- i.e., contract creation uint period; uint startOfEpoch; /***** DATA STRUCTURES *****/ struct Pledge { address creator; uint weiPerPeriod; uint afterLastPeriod; // first period s.t. pledge makes no payment bool initialized; } mapping (address => uint) supporterBalances; mapping (address => uint) creatorBalances; // supporter => (creator => pledge) mapping(address => mapping(address => Pledge)) pledges; // creator => (periodNumber => payment) mapping (address => mapping(uint => uint)) expectedPayments; mapping (address => uint) afterLastWithdrawalPeriod; /***** HELPER FUNCTIONS *****/ function Pethreon(uint _period) { startOfEpoch = now; period = _period; } function currentPeriod() internal view returns (uint periodNumber) { return (now - startOfEpoch) / period; } /* // TODO: get expected payments in batch (can't return uint[]?) function getExpectedPayment(uint period) constant returns (uint expectedPayment) { return (period < afterLastWithdrawalPeriod[msg.sender]) ? 0 : expectedPayments[msg.sender][period]; } */ /***** DEPOSIT & WITHDRAW *****/ // Get your (yet unpledged) balance as a supporter function balanceAsSupporter() public view returns (uint) { return supporterBalances[msg.sender]; } function balanceAsCreator() public view returns (uint) { // sum up all expected payments from all pledges from all previous periods uint256 amount = 0; for (var period = afterLastWithdrawalPeriod[msg.sender]; period < currentPeriod(); period++) { amount += expectedPayments[msg.sender][period]; } return amount; } // deposit ether to be used in future pledges function deposit() public payable returns (uint newBalance) { supporterBalances[msg.sender] += msg.value; SupporterDeposited(currentPeriod(), msg.sender, msg.value); return supporterBalances[msg.sender]; } // withdraw ether (generic function) function withdraw(bool isSupporter, uint amount) internal returns (uint newBalance) { var balances = isSupporter ? supporterBalances : creatorBalances; uint oldBalance = balances[msg.sender]; if (balances[msg.sender] < amount) return oldBalance; balances[msg.sender] -= amount; if (!msg.sender.send(amount)) { balances[msg.sender] += amount; return oldBalance; } return balances[msg.sender]; } // Supporter can choose how much to withdraw function withdrawAsSupporter(uint amount) public { withdraw(true, amount); SupporterWithdrew(currentPeriod(), msg.sender, amount); } // Creator can only withdraw the full amount available (keeping it simple!) function withdrawAsCreator() public { var amount = balanceAsCreator(); afterLastWithdrawalPeriod[msg.sender] = currentPeriod(); withdraw(false, amount); CreatorWithdrew(currentPeriod(), msg.sender, amount); } /***** PLEDGES *****/ function canPledge(uint _weiPerPeriod, uint _periods) internal view returns (bool enoughFunds) { return (supporterBalances[msg.sender] >= _weiPerPeriod * _periods); } function createPledge(address _creator, uint _weiPerPeriod, uint _periods) public { // must have enough funds require(canPledge(_weiPerPeriod, _periods)); // can't pledge twice for same creator (for simplicity) // to change pledge parameters, cancel it and create a new one require(!pledges[msg.sender][_creator].initialized); // update creator's mapping of future payments for (uint period = currentPeriod(); period < _periods; period++) { expectedPayments[_creator][period] += _weiPerPeriod; } // store the data structure so that supporter can cancel pledge var pledge = Pledge({ creator: _creator, weiPerPeriod: _weiPerPeriod, afterLastPeriod: currentPeriod() + _periods, initialized: true }); pledges[msg.sender][_creator] = pledge; supporterBalances[msg.sender] -= _weiPerPeriod * _periods; PledgeCreated(currentPeriod(), _creator, msg.sender, _weiPerPeriod, _periods); } function cancelPledge(address _creator) public { var pledge = pledges[msg.sender][_creator]; require(pledge.initialized); supporterBalances[msg.sender] += pledge.weiPerPeriod * (pledge.afterLastPeriod - currentPeriod()); for (uint period = currentPeriod(); period < pledge.afterLastPeriod; period++) { expectedPayments[_creator][period] -= pledge.weiPerPeriod; } delete pledges[msg.sender][_creator]; PledgeCancelled(currentPeriod(), _creator, msg.sender); } function myPledgeTo(address _creator) public view returns (uint weiPerPeriod, uint afterLastPeriod) { var pledge = pledges[msg.sender][_creator]; return (pledge.weiPerPeriod, pledge.afterLastPeriod); } }
TODO: get expected payments in batch (can't return uint[]?)
function getExpectedPayment(uint period) constant returns (uint expectedPayment) { return (period < afterLastWithdrawalPeriod[msg.sender]) ? 0 : expectedPayments[msg.sender][period]; }
7,288,879
/* Owned.sol Pacio Core Ltd https://www.pacio.io 2017.03.04 djh Originally created 2017.08.16 Brought into use for Pacio token sale use 2017.08.22 Logging revised Owned is a Base Contract for contracts that are: • "owned" • can have their owner changed by a call to ChangeOwner() by the owner • can be paused from an active state by a call to Pause() by the owner • can be resumed from a paused state by a call to Resume() by the owner Modifier functions available for use here and in child contracts are: • IsOwner() which throws if called by other than the current owner • IsActive() which throws if called when the contract is paused Changes of owner are logged via event LogOwnerChange(address indexed previousOwner, address newOwner) */ pragma solidity ^0.4.15; contract Owned { address public ownerA; // Contract owner bool public pausedB; // Constructor NOT payable // ----------- function Owned() { ownerA = msg.sender; } // Modifier functions // ------------------ modifier IsOwner { require(msg.sender == ownerA); _; } modifier IsActive { require(!pausedB); _; } // Events // ------ event LogOwnerChange(address indexed PreviousOwner, address NewOwner); event LogPaused(); event LogResumed(); // State changing public methods // ----------------------------- // Change owner function ChangeOwner(address vNewOwnerA) IsOwner { require(vNewOwnerA != address(0) && vNewOwnerA != ownerA); LogOwnerChange(ownerA, vNewOwnerA); ownerA = vNewOwnerA; } // Pause function Pause() IsOwner { pausedB = true; // contract has been paused LogPaused(); } // Resume function Resume() IsOwner { pausedB = false; // contract has been resumed LogResumed(); } } // End Owned contract // DSMath.sol // From https://dappsys.readthedocs.io/en/latest/ds_math.html // Reduced version - just the fns used by Pacio // Copyright (C) 2015, 2016, 2017 DappHub, LLC // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // 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 (express or implied). contract DSMath { /* standard uint256 functions */ function add(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x + y) >= x); } function sub(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x - y) <= x); } function mul(uint256 x, uint256 y) constant internal returns (uint256 z) { z = x * y; assert(x == 0 || z / x == y); } // div isn't needed. Only error case is div by zero and Solidity throws on that // function div(uint256 x, uint256 y) constant internal returns (uint256 z) { // z = x / y; // } // subMaxZero(x, y) // Pacio addition to avoid throwing if a subtraction goes below zero and return 0 in that case. function subMaxZero(uint256 x, uint256 y) constant internal returns (uint256 z) { if (y > x) z = 0; else z = x - y; } } // ERC20Token.sol 2017.08.16 started // 2017.10.07 isERC20Token changed to isEIP20Token /* ERC Token Standard #20 Interface https://github.com/ethereum/EIPs/issues/20 https://github.com/frozeman/EIPs/blob/94bc4311e889c2c58c561c074be1483f48ac9374/EIPS/eip-20-token-standard.md Using Dappsys naming style of 3 letter names: src, dst, guy, wad */ contract ERC20Token is Owned, DSMath { // Data bool public constant isEIP20Token = true; // Interface declaration uint public totalSupply; // Total tokens minted bool public saleInProgressB; // when true stops transfers mapping(address => uint) internal iTokensOwnedM; // Tokens owned by an account mapping(address => mapping (address => uint)) private pAllowedM; // Owner of account approves the transfer of an amount to another account // ERC20 Events // ============ // Transfer // Triggered when tokens are transferred. event Transfer(address indexed src, address indexed dst, uint wad); // Approval // Triggered whenever approve(address spender, uint wad) is called. event Approval(address indexed Sender, address indexed Spender, uint Wad); // ERC20 Methods // ============= // Public Constant Methods // ----------------------- // balanceOf() // Returns the token balance of account with address guy function balanceOf(address guy) public constant returns (uint) { return iTokensOwnedM[guy]; } // allowance() // Returns the number of tokens approved by guy that can be transferred ("spent") by spender function allowance(address guy, address spender) public constant returns (uint) { return pAllowedM[guy][spender]; } // Modifier functions // ------------------ modifier IsTransferOK(address src, address dst, uint wad) { require(!saleInProgressB // Sale not in progress && !pausedB // IsActive && iTokensOwnedM[src] >= wad // Source has the tokens available // && wad > 0 // Non-zero transfer No! The std says: Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event && dst != src // Destination is different from source && dst != address(this) // Not transferring to this token contract && dst != ownerA); // Not transferring to the owner of this contract - the token sale contract _; } // State changing public methods made pause-able and with call logging // ----------------------------- // transfer() // Transfers wad of sender's tokens to another account, address dst // No need for overflow check given that totalSupply is always far smaller than max uint function transfer(address dst, uint wad) IsTransferOK(msg.sender, dst, wad) returns (bool) { iTokensOwnedM[msg.sender] -= wad; // There is no need to check this for underflow via a sub() call given the IsTransferOK iTokensOwnedM[src] >= wad check iTokensOwnedM[dst] = add(iTokensOwnedM[dst], wad); Transfer(msg.sender, dst, wad); return true; } // transferFrom() // Sender transfers wad tokens from src account src to dst account, if // sender had been approved by src for a transfer of >= wad tokens from src's account // by a prior call to approve() with that call's sender being this calls src, // and its spender being this call's sender. function transferFrom(address src, address dst, uint wad) IsTransferOK(src, dst, wad) returns (bool) { require(pAllowedM[src][msg.sender] >= wad); // Transfer is approved iTokensOwnedM[src] -= wad; // There is no need to check this for underflow given the require above pAllowedM[src][msg.sender] -= wad; // There is no need to check this for underflow given the require above iTokensOwnedM[dst] = add(iTokensOwnedM[dst], wad); Transfer(src, dst, wad); return true; } // approve() // Approves the passed address (of spender) to spend up to wad tokens on behalf of msg.sender, // in one or more transferFrom() calls // If this function is called again it overwrites the current allowance with wad. function approve(address spender, uint wad) IsActive 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 // djh: This appears to be of doubtful value, and is not used in the Dappsys library though it is in the Zeppelin one. Removed. // require((wad == 0) || (pAllowedM[msg.sender][spender] == 0)); pAllowedM[msg.sender][spender] = wad; Approval(msg.sender, spender, wad); return true; } } // End ERC20Token contracts // PacioToken.sol 2017.08.22 started /* The Pacio Token named PIOE for the Ethereum version Follows the EIP20 standard: https://github.com/frozeman/EIPs/blob/94bc4311e889c2c58c561c074be1483f48ac9374/EIPS/eip-20-token-standard.md 2017.10.08 Changed to suit direct deployment rather than being created via the PacioICO constructor, so that Etherscan can recognise it. */ contract PacioToken is ERC20Token { // enum NFF { // Founders/Foundation enum // Founders, // 0 Pacio Founders // Foundatn} // 1 Pacio Foundation string public constant name = "Pacio Token"; string public constant symbol = "PIOE"; uint8 public constant decimals = 12; uint public tokensIssued; // Tokens issued - tokens in circulation uint public tokensAvailable; // Tokens available = total supply less allocated and issued tokens uint public contributors; // Number of contributors uint public founderTokensAllocated; // Founder tokens allocated uint public founderTokensVested; // Founder tokens vested. Same as iTokensOwnedM[pFounderToksA] until tokens transferred. Unvested tokens = founderTokensAllocated - founderTokensVested uint public foundationTokensAllocated; // Foundation tokens allocated uint public foundationTokensVested; // Foundation tokens vested. Same as iTokensOwnedM[pFoundationToksA] until tokens transferred. Unvested tokens = foundationTokensAllocated - foundationTokensVested bool public icoCompleteB; // Is set to true when both presale and full ICO are complete. Required for vesting of founder and foundation tokens and transfers of PIOEs to PIOs address private pFounderToksA; // Address for Founder tokens issued address private pFoundationToksA; // Address for Foundation tokens issued // Events // ------ event LogIssue(address indexed Dst, uint Picos); event LogSaleCapReached(uint TokensIssued); // not tokensIssued just to avoid compiler Warning: This declaration shadows an existing declaration event LogIcoCompleted(); event LogBurn(address Src, uint Picos); event LogDestroy(uint Picos); // No Constructor // -------------- // Initialisation/Settings Methods IsOwner but not IsActive // ------------------------------- // Initialise() // To be called by deployment owner to change ownership to the sale contract, and do the initial allocations and minting. // Can only be called once. If the sale contract changes but the token contract stays the same then ChangeOwner() can be called via PacioICO.ChangeTokenContractOwner() to change the owner to the new contract function Initialise(address vNewOwnerA) { // IsOwner c/o the super.ChangeOwner() call require(totalSupply == 0); // can only be called once super.ChangeOwner(vNewOwnerA); // includes an IsOwner check so don't need to repeat it here founderTokensAllocated = 10**20; // 10% or 100 million = 1e20 Picos foundationTokensAllocated = 10**20; // 10% or 100 million = 1e20 Picos This call sets tokensAvailable // Equivalent of Mint(10**21) which can't be used here as msg.sender is the old (deployment) owner // 1 Billion PIOEs = 1e21 Picos, all minted) totalSupply = 10**21; // 1 Billion PIOEs = 1e21 Picos, all minted) iTokensOwnedM[ownerA] = 10**21; tokensAvailable = 8*(10**20); // 800 million [String: '800000000000000000000'] s: 1, e: 20, c: [ 8000000 ] } // From the EIP20 Standard: A token contract which creates new tokens SHOULD trigger a Transfer event with the _from address set to 0x0 when tokens are created. Transfer(0x0, ownerA, 10**21); // log event 0x0 from == minting } // Mint() // PacioICO() includes a Mint() fn to allow manual calling of this if necessary e.g. re full ICO going over the cap function Mint(uint picos) IsOwner { totalSupply = add(totalSupply, picos); iTokensOwnedM[ownerA] = add(iTokensOwnedM[ownerA], picos); tokensAvailable = subMaxZero(totalSupply, tokensIssued + founderTokensAllocated + foundationTokensAllocated); // From the EIP20 Standard: A token contract which creates new tokens SHOULD trigger a Transfer event with the _from address set to 0x0 when tokens are created. Transfer(0x0, ownerA, picos); // log event 0x0 from == minting } // PrepareForSale() // stops transfers and allows purchases function PrepareForSale() IsOwner { require(!icoCompleteB); // Cannot start selling again once ICO has been set to completed saleInProgressB = true; // stops transfers } // ChangeOwner() // To be called by owner to change the token contract owner, expected to be to a sale contract // Transfers any minted tokens from old to new sale contract function ChangeOwner(address vNewOwnerA) { // IsOwner c/o the super.ChangeOwner() call transfer(vNewOwnerA, iTokensOwnedM[ownerA]); // includes checks super.ChangeOwner(vNewOwnerA); // includes an IsOwner check so don't need to repeat it here } // Public Constant Methods // ----------------------- // None. Used public variables instead which result in getter functions // State changing public methods made pause-able and with call logging // ----------------------------- // Issue() // Transfers picos tokens to dst to issue them. IsOwner because this is expected to be called from the token sale contract function Issue(address dst, uint picos) IsOwner IsActive returns (bool) { require(saleInProgressB // Sale is in progress && iTokensOwnedM[ownerA] >= picos // Owner has the tokens available // && picos > 0 // Non-zero issue No need to check for this && dst != address(this) // Not issuing to this token contract && dst != ownerA); // Not issuing to the owner of this contract - the token sale contract if (iTokensOwnedM[dst] == 0) contributors++; iTokensOwnedM[ownerA] -= picos; // There is no need to check this for underflow via a sub() call given the iTokensOwnedM[ownerA] >= picos check iTokensOwnedM[dst] = add(iTokensOwnedM[dst], picos); tokensIssued = add(tokensIssued, picos); tokensAvailable = subMaxZero(tokensAvailable, picos); // subMaxZero() in case a sale goes over, only possible for full ICO, when cap is for all available tokens. LogIssue(dst, picos); // If that should happen,may need to mint some more PIOEs to allow founder and foundation vesting to complete. return true; } // SaleCapReached() // To be be called from the token sale contract when a cap (pre or full) is reached // Allows transfers function SaleCapReached() IsOwner IsActive { saleInProgressB = false; // allows transfers LogSaleCapReached(tokensIssued); } // Functions for manual calling via same name function in PacioICO() // ================================================================= // IcoCompleted() // To be be called manually via PacioICO after full ICO ends. Could be called before cap is reached if .... function IcoCompleted() IsOwner IsActive { require(!icoCompleteB); saleInProgressB = false; // allows transfers icoCompleteB = true; LogIcoCompleted(); } // SetFFSettings(address vFounderTokensA, address vFoundationTokensA, uint vFounderTokensAllocation, uint vFoundationTokensAllocation) // Allows setting Founder and Foundation addresses (or changing them if an appropriate transfer has been done) // plus optionally changing the allocations which are set by the constructor, so that they can be varied post deployment if required re a change of plan // All values are optional - zeros can be passed // Must have been called with non-zero Founder and Foundation addresses before Founder and Foundation vesting can be done function SetFFSettings(address vFounderTokensA, address vFoundationTokensA, uint vFounderTokensAllocation, uint vFoundationTokensAllocation) IsOwner { if (vFounderTokensA != address(0)) pFounderToksA = vFounderTokensA; if (vFoundationTokensA != address(0)) pFoundationToksA = vFoundationTokensA; if (vFounderTokensAllocation > 0) assert((founderTokensAllocated = vFounderTokensAllocation) >= founderTokensVested); if (vFoundationTokensAllocation > 0) assert((foundationTokensAllocated = vFoundationTokensAllocation) >= foundationTokensVested); tokensAvailable = totalSupply - founderTokensAllocated - foundationTokensAllocated - tokensIssued; } // VestFFTokens() // To vest Founder and/or Foundation tokens // 0 can be passed meaning skip that one // No separate event as the LogIssue event can be used to trace vesting transfers // To be be called manually via PacioICO function VestFFTokens(uint vFounderTokensVesting, uint vFoundationTokensVesting) IsOwner IsActive { require(icoCompleteB); // ICO must be completed before vesting can occur. djh?? Add other time restriction? if (vFounderTokensVesting > 0) { assert(pFounderToksA != address(0)); // Founders token address must have been set assert((founderTokensVested = add(founderTokensVested, vFounderTokensVesting)) <= founderTokensAllocated); iTokensOwnedM[ownerA] = sub(iTokensOwnedM[ownerA], vFounderTokensVesting); iTokensOwnedM[pFounderToksA] = add(iTokensOwnedM[pFounderToksA], vFounderTokensVesting); LogIssue(pFounderToksA, vFounderTokensVesting); tokensIssued = add(tokensIssued, vFounderTokensVesting); } if (vFoundationTokensVesting > 0) { assert(pFoundationToksA != address(0)); // Foundation token address must have been set assert((foundationTokensVested = add(foundationTokensVested, vFoundationTokensVesting)) <= foundationTokensAllocated); iTokensOwnedM[ownerA] = sub(iTokensOwnedM[ownerA], vFoundationTokensVesting); iTokensOwnedM[pFoundationToksA] = add(iTokensOwnedM[pFoundationToksA], vFoundationTokensVesting); LogIssue(pFoundationToksA, vFoundationTokensVesting); tokensIssued = add(tokensIssued, vFoundationTokensVesting); } // Does not affect tokensAvailable as these tokens had already been allowed for in tokensAvailable when allocated } // Burn() // For use when transferring issued PIOEs to PIOs // To be be called manually via PacioICO or from a new transfer contract to be written which is set to own this one function Burn(address src, uint picos) IsOwner IsActive { require(icoCompleteB); iTokensOwnedM[src] = subMaxZero(iTokensOwnedM[src], picos); tokensIssued = subMaxZero(tokensIssued, picos); totalSupply = subMaxZero(totalSupply, picos); LogBurn(src, picos); // Does not affect tokensAvailable as these are issued tokens that are being burnt } // Destroy() // For use when transferring unissued PIOEs to PIOs // To be be called manually via PacioICO or from a new transfer contract to be written which is set to own this one function Destroy(uint picos) IsOwner IsActive { require(icoCompleteB); totalSupply = subMaxZero(totalSupply, picos); tokensAvailable = subMaxZero(tokensAvailable, picos); LogDestroy(picos); } // Fallback function // ================= // No sending ether to this contract! // Not payable so trying to send ether will throw function() { revert(); // reject any attempt to access the token contract other than via the defined methods with their testing for valid access } } // End PacioToken contract // PacioICO.sol 2017.08.16 started /* Token sale for Pacio.io Works with PacioToken.sol as the contract for the Pacio Token The contract is intended to handle both presale and full ICO, though, if necessary a new contract could be used for the full ICO, with the token contract unchanged apart from its owner. Min purchase Ether 0.1 No end date - just cap or pause Decisions --------- No threshold 2017.10.07 Removed ForwardFunds() and made forward happen on each receipt Changed from use of fallback fn to specific Buy() fn and made fallback revert, re best practices re fallback fn use. Since fallback functions can be misused or abused, Vitalik Buterin suggested "establishing as a convention that fallback functions should generally not be used except in very specific cases." 2017.10.08 Changed to deploy PacioToken contract directly rather than create it via the constructor here, and then to pass the address to PrepareToStart() as part of getting Etherscan te recognise the Token contract */ contract PacioICO is Owned, DSMath { string public name; // Contract name uint public startTime; // start time of the sale uint public picosCap; // Cap for the sale uint public picosSold; // Cumulative Picos sold which should == PIOE.pTokensIssued uint public picosPerEther; // 3,000,000,000,000,000 for ETH = $300 and target PIOE price = $0.10 uint public weiRaised; // cumulative wei raised PacioToken public PIOE; // the Pacio token contract address private pPCwalletA; // address of the Pacio Core wallet to receive funds raised // Constructor not payable // ----------- // function PacioICO() { pausedB = true; // start paused } // Events // ------ event LogPrepareToStart(string Name, uint StartTime, uint PicosCap, PacioToken TokenContract, address PCwallet); event LogSetPicosPerEther(uint PicosPerEther); event LogChangePCWallet(address PCwallet); event LogSale(address indexed Purchaser, uint SaleWei, uint Picos); event LogAllocate(address indexed Supplier, uint SuppliedWei, uint Picos); event LogSaleCapReached(uint WeiRaised, uint PicosSold); // PrepareToStart() // -------------- // To be called manually by owner just prior to the start of the presale or the full ICO // Can also be called by owner to adjust settings. With care!! function PrepareToStart(string vNameS, uint vStartTime, uint vPicosCap, uint vPicosPerEther, PacioToken vTokenA, address vPCwalletA) IsOwner { require(vTokenA != address(0) && vPCwalletA != address(0)); name = vNameS; // Pacio Presale | Pacio Token Sale startTime = vStartTime; picosCap = vPicosCap; // Cap for the sale, 20 Million PIOEs = 20,000,000,000,000,000,000 = 20**19 Picos for the Presale PIOE = vTokenA; // The token contract pPCwalletA = vPCwalletA; // Pacio Code wallet to receive funds pausedB = false; PIOE.PrepareForSale(); // stops transfers LogPrepareToStart(vNameS, vStartTime, vPicosCap, vTokenA, vPCwalletA); SetPicosPerEther(vPicosPerEther); } // Public Constant Methods // ----------------------- // None. Used public variables instead which result in getter functions // State changing public method made pause-able // ---------------------------- // Buy() // Fn to be called to buy PIOEs function Buy() payable IsActive { require(now >= startTime); // sale is running (in conjunction with the IsActive test) require(msg.value >= 0.1 ether); // sent >= the min uint picos = mul(picosPerEther, msg.value) / 10**18; // Picos = Picos per ETH * Wei / 10^18 <=== calc for integer arithmetic as in Solidity weiRaised = add(weiRaised, msg.value); pPCwalletA.transfer(this.balance); // throws on failure PIOE.Issue(msg.sender, picos); LogSale(msg.sender, msg.value, picos); picosSold += picos; // ok wo overflow protection as PIOE.Issue() would have thrown on overflow if (picosSold >= picosCap) { // Cap reached so end the sale pausedB = true; PIOE.SaleCapReached(); // Allows transfers LogSaleCapReached(weiRaised, picosSold); } } // Functions to be called Manually // =============================== // SetPicosPerEther() // Fn to be called daily (hourly?) or on significant Ether price movement to set the Pico price function SetPicosPerEther(uint vPicosPerEther) IsOwner { picosPerEther = vPicosPerEther; // 3,000,000,000,000,000 for ETH = $300 and target PIOE price = $0.10 LogSetPicosPerEther(picosPerEther); } // ChangePCWallet() // Fn to be called to change the PC Wallet to receive funds raised. This is set initially via PrepareToStart() function ChangePCWallet(address vPCwalletA) IsOwner { require(vPCwalletA != address(0)); pPCwalletA = vPCwalletA; LogChangePCWallet(vPCwalletA); } // Allocate() // Allocate in lieu for goods or services or fiat supplied valued at wad wei in return for picos issued. Not payable // no picosCap check function Allocate(address vSupplierA, uint wad, uint picos) IsOwner IsActive { PIOE.Issue(vSupplierA, picos); LogAllocate(vSupplierA, wad, picos); picosSold += picos; // ok wo overflow protection as PIOE.Issue() would have thrown on overflow } // Token Contract Functions to be called Manually via Owner calls to ICO Contract // ============================================================================== // ChangeTokenContractOwner() // To be called manually if a new sale contract is deployed to change the owner of the PacioToken contract to it. // Expects the sale contract to have been paused // Calling ChangeTokenContractOwner() will stop calls from the old sale contract to token contract IsOwner functions from working function ChangeTokenContractOwner(address vNewOwnerA) IsOwner { require(pausedB); PIOE.ChangeOwner(vNewOwnerA); } // PauseTokenContract() // To be called manually to pause the token contract function PauseTokenContract() IsOwner { PIOE.Pause(); } // ResumeTokenContract() // To be called manually to resume the token contract function ResumeTokenContract() IsOwner { PIOE.Resume(); } // Mint() // To be called manually if necessary e.g. re full ICO going over the cap // Expects the sale contract to have been paused function Mint(uint picos) IsOwner { require(pausedB); PIOE.Mint(picos); } // IcoCompleted() // To be be called manually after full ICO ends. Could be called before cap is reached if .... // Expects the sale contract to have been paused function IcoCompleted() IsOwner { require(pausedB); PIOE.IcoCompleted(); } // SetFFSettings() // Allows setting Founder and Foundation addresses (or changing them if an appropriate transfer has been done) // plus optionally changing the allocations which are set by the PacioToken constructor, so that they can be varied post deployment if required re a change of plan // All values are optional - zeros can be passed // Must have been called with non-zero Founder and Foundation addresses before Founder and Foundation vesting can be done function SetFFSettings(address vFounderTokensA, address vFoundationTokensA, uint vFounderTokensAllocation, uint vFoundationTokensAllocation) IsOwner { PIOE.SetFFSettings(vFounderTokensA, vFoundationTokensA, vFounderTokensAllocation, vFoundationTokensAllocation); } // VestFFTokens() // To vest Founder and/or Foundation tokens // 0 can be passed meaning skip that one // SetFFSettings() must have been called with non-zero Founder and Foundation addresses before this fn can be used function VestFFTokens(uint vFounderTokensVesting, uint vFoundationTokensVesting) IsOwner { PIOE.VestFFTokens(vFounderTokensVesting, vFoundationTokensVesting); } // Burn() // For use when transferring issued PIOEs to PIOs // To be replaced by a new transfer contract to be written which is set to own the PacioToken contract function Burn(address src, uint picos) IsOwner { PIOE.Burn(src, picos); } // Destroy() // For use when transferring unissued PIOEs to PIOs // To be replaced by a new transfer contract to be written which is set to own the PacioToken contract function Destroy(uint picos) IsOwner { PIOE.Destroy(picos); } // Fallback function // ================= // No sending ether to this contract! // Not payable so trying to send ether will throw function() { revert(); // reject any attempt to access the token contract other than via the defined methods with their testing for valid access } } // End PacioICO contract
IsOwner c/o the super.ChangeOwner() call
function Initialise(address vNewOwnerA) {
12,650,259
pragma solidity ^0.5.13; pragma experimental ABIEncoderV2; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "./ValSafeMath.sol"; import "./ILiquidator.sol"; import "@trusttoken/registry/contracts/Registry.sol"; import "wjm-airswap-swap/contracts/Swap.sol"; /** * @dev Program that executes a trade * TradeExecutor is a contract that executes a trade * It's much cheaper to deploy and run a contract than to * execute in the liquidator * TradeExecutor is called via delegatecall */ interface TradeExecutor { } /** * @dev Uniswap * This is nessesary since Uniswap is written in vyper. */ interface UniswapV1 { function tokenToExchangeSwapInput(uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, UniswapV1 exchangeAddress) external returns (uint256 tokensBought); function tokenToExchangeTransferInput(uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address recipient, UniswapV1 exchangeAddress) external returns (uint256 tokensBought); function tokenToExchangeSwapOutput(uint256 tokensBought, uint256 maxTokensSold, uint256 maxEthSold, uint256 deadline, UniswapV1 exchangeAddress) external returns (uint256 tokensSold); function tokenToExchangeTransferOutput(uint256 tokensBought, uint256 maxTokensSold, uint256 maxEthSold, uint256 deadline, address recipient, UniswapV1 exchangeAddress) external returns (uint256 tokensSold); } /** * @dev Uniswap Factory * This is nessesary since Uniswap is written in vyper. */ interface UniswapV1Factory { function getExchange(IERC20 token) external returns (UniswapV1); } /** * @title Abstract Liquidator for Airswap and Uniswap * @dev Liquidate staked tokenns on uniswap and airswap * Airswap uses domainSeparators to validate transactions and prevent replay protection * When signing an airswap order we require specification of which validator we are using. * This is because there are multiple instances of AirswapV2. * StakingOpportunityFactory does not create a Liquidator, rather this must be created * Outside of the factory. * prune() removes all orders that would fail from */ contract ALiquidatorAirswap is ILiquidator { using ValSafeMath for uint256; // owner, attributes, and domain separators address public owner; address public pendingOwner; mapping (address => uint256) attributes; // domain separators is a paramater of airswap synced as an attribute // when you register an airswap validator you need to register domain separators // 32 bytes in data that you sign which corresponds to contract signed for // used for replay protection, examples of this in test files // mappings updated in syncAttributeValue // signedTypedData standard mapping (address => bytes32) domainSeparators; // Orders are contracts that execute airswaps // We DELEGATECALL into orders to invoke them // Orders are stored in this mapping as a sorted singly linkedlist // Invariant: orders are sorted by greatest price // Linked list head and tail are mapped to zero // It's much much cheaper to deploy a contract to execute the trade mapping (/* TradeExecutor */ address => TradeExecutor) public next; // constants bytes32 constant APPROVED_BENEFICIARY = "approvedBeneficiary"; uint256 constant LIQUIDATOR_CAN_RECEIVE = 0xff00000000000000000000000000000000000000000000000000000000000000; uint256 constant LIQUIDATOR_CAN_RECEIVE_INV = 0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // part of signature so that signing for airswap doesn't sign for all airswap instances bytes32 constant AIRSWAP_VALIDATOR = "AirswapValidatorDomain"; uint256 constant MAX_UINT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant MAX_UINT128 = 0xffffffffffffffffffffffffffffffff; bytes1 constant AIRSWAP_AVAILABLE = bytes1(0x0); bytes2 EIP191_HEADER = 0x1901; // internal variables implemented as storage by Liquidator // these variables must be known at construction time // Liquidator is the actual implementation of ALiquidator /** @dev Get output token (token to get from liqudiation exchange). */ function outputToken() internal view returns (IERC20); /** @dev Get stake token (token to be liquidated). */ function stakeToken() internal view returns (IERC20); /** @dev Output token on uniswap. */ function outputUniswapV1() internal view returns (UniswapV1); /** @dev Stake token on uniswap. */ function stakeUniswapV1() internal view returns (UniswapV1); /** @dev Contract registry. */ function registry() internal view returns (Registry); /** @dev Address of staking pool. */ function pool() internal view returns (address); /** * @dev implementation constructor needs to call initialize * Here we approve transfers to uniswap for the staking and output token */ function initialize() internal { outputToken().approve(address(outputUniswapV1()), MAX_UINT); stakeToken().approve(address(stakeUniswapV1()), MAX_UINT); } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event LimitOrder(TradeExecutor indexed order); event Fill(TradeExecutor indexed order); event Cancel(TradeExecutor indexed order); event Liquidated(uint256 indexed stakeAmount, uint256 indexed debtAmount); // used to track why a liquidation failed event LiquidationError(TradeExecutor indexed order, bytes error); modifier onlyRegistry { require(msg.sender == address(registry()), "only registry"); _; } modifier onlyPendingOwner() { require(msg.sender == pendingOwner, "only pending owner"); _; } modifier onlyOwner() { require(msg.sender == owner, "only owner"); _; } function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } /** * @dev Two flags are supported by this function: * AIRSWAP_VALIDATOR and APPROVED_BENEFICIARY * Can sync by saying this contract is the registry or sync from registry directly. * Registry decides what is a valid airswap. */ function syncAttributeValue(address _account, bytes32 _attribute, uint256 _value) external onlyRegistry { if (_attribute == AIRSWAP_VALIDATOR) { if (_value > 0) { // register domain separator and approve validator to spend stakeToken().approve(_account, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); domainSeparators[_account] = bytes32(_value); } else { stakeToken().approve(_account, 0); domainSeparators[_account] = bytes32(0); } } else if (_attribute == APPROVED_BENEFICIARY) { // approved beneficiary flag defines whether someone can recieve if (_value > 0) { attributes[_account] |= LIQUIDATOR_CAN_RECEIVE; } else { attributes[_account] &= LIQUIDATOR_CAN_RECEIVE_INV; } } } struct UniswapState { UniswapV1 uniswap; uint256 etherBalance; uint256 tokenBalance; } /** * @dev Calculate how much output we get for a stake input amount * Much cheaper to do this logic ourselves locally than an external call * Allows us to do this multiple times in one transaction * See ./uniswap/uniswap_exchange.vy */ function outputForUniswapV1Input(uint256 stakeInputAmount, UniswapState memory outputUniswapV1State, UniswapState memory stakeUniswapV1State) internal pure returns (uint256 outputAmount) { uint256 inputAmountWithFee = 997 * stakeInputAmount; inputAmountWithFee = 997 * (inputAmountWithFee * stakeUniswapV1State.etherBalance) / (stakeUniswapV1State.tokenBalance * 1000 + inputAmountWithFee); outputAmount = (inputAmountWithFee * outputUniswapV1State.tokenBalance) / (outputUniswapV1State.etherBalance * 1000 + inputAmountWithFee); } /** * @dev Calcualte how much input we need to get a desired output * Is able to let us know if there is slippage in uniswap exchange rate * and continue with Airswap * See./uniswap/uniswap_exchange.vy */ function inputForUniswapV1Output(uint256 outputAmount, UniswapState memory outputUniswapV1State, UniswapState memory stakeUniswapV1State) internal pure returns (uint256 inputAmount) { if (outputAmount >= outputUniswapV1State.tokenBalance) { return MAX_UINT128; } uint256 ethNeeded = (outputUniswapV1State.etherBalance * outputAmount * 1000) / (997 * (outputUniswapV1State.tokenBalance - outputAmount)) + 1; if (ethNeeded >= stakeUniswapV1State.etherBalance) { return MAX_UINT128; } inputAmount = (stakeUniswapV1State.tokenBalance * ethNeeded * 1000) / (997 * (stakeUniswapV1State.etherBalance - ethNeeded)) + 1; } function head() public view returns (TradeExecutor) { return next[address(0)]; } /** * @dev Transfer stake without liquidation * requires LIQUIDATOR_CAN_RECEIVE flag (recipient must be registered) */ function reclaimStake(address _destination, uint256 _stake) external onlyOwner { require(attributes[_destination] & LIQUIDATOR_CAN_RECEIVE != 0, "unregistered recipient"); stakeToken().transferFrom(pool(), _destination, _stake); } /** * @dev Award stake tokens to stakers. * Transfer to the pool without creating a staking position. * Allows us to reward as staking or reward token. */ function returnStake(address _from, uint256 balance) external { stakeToken().transferFrom(_from, pool(), balance); } /** * @dev Sells stake for underlying asset and pays to destination. * Use airswap trades as long as they're better than uniswap. * Contract won't slip Uniswap this way. * If we reclaim more than we actually owe we award to stakers. * Not possible to convert back into TrustTokens here. */ function reclaim(address _destination, int256 _debt) external onlyOwner { require(_debt > 0, "Must reclaim positive amount"); require(_debt < int256(MAX_UINT128), "reclaim amount too large"); require(attributes[_destination] & LIQUIDATOR_CAN_RECEIVE != 0, "unregistered recipient"); // get balance of stake pool address stakePool = pool(); uint256 remainingStake = stakeToken().balanceOf(stakePool); // withdraw to liquidator require(stakeToken().transferFrom(stakePool, address(this), remainingStake), "unapproved"); // load uniswap state for output and staked token UniswapState memory outputUniswapV1State; UniswapState memory stakeUniswapV1State; outputUniswapV1State.uniswap = outputUniswapV1(); outputUniswapV1State.etherBalance = address(outputUniswapV1State.uniswap).balance; outputUniswapV1State.tokenBalance = outputToken().balanceOf(address(outputUniswapV1State.uniswap)); stakeUniswapV1State.uniswap = stakeUniswapV1(); stakeUniswapV1State.etherBalance = address(stakeUniswapV1State.uniswap).balance; stakeUniswapV1State.tokenBalance = stakeToken().balanceOf(address(stakeUniswapV1State.uniswap)); // calculate remaining debt int256 remainingDebt = _debt; // set order linkedlist to head TradeExecutor curr = head(); // walk through iterator while we still have orders and gas while (curr != TradeExecutor(0) && gasleft() > SWAP_GAS_COST) { // load order using airswapOrderInfo which copies end of order contract into memory // now we have the order in memory. This is very cheap (<1000 gas) // ~23x more efficient than using storage FlatOrder memory order = airswapOrderInfo(curr); // if order tries to buy more stake than we have we cancel order // othwerwise continue to walk through orders if (order.senderAmount <= remainingStake) { // check price using cross product // checks if we get a better deal in uniswap if (inputForUniswapV1Output(uint256(remainingDebt), outputUniswapV1State, stakeUniswapV1State) * order.signerAmount < order.senderAmount * uint256(remainingDebt)) { // remaining orders are not as good as uniswap break; } // use delegatecall to process order from our address // we are the only people who can execute this order (bool success, bytes memory returnValue) = address(curr).delegatecall(""); // on success, emit fill event and update state // otherwise cancel and emit liqudiation error // an order either cancels or fills if (success) { emit Fill(curr); // calculate remaining debt remainingDebt -= int256(order.signerAmount); remainingStake -= order.senderAmount; // underflow not possible because airswap transfer succeeded // emit liquidation and break if no more debt emit Liquidated(order.senderAmount, order.signerAmount); if (remainingDebt <= 0) { break; } } else { emit Cancel(curr); emit LiquidationError(curr, returnValue); } } else { emit Cancel(curr); } // advance through linkedlist by setting head to next item address prev = address(curr); curr = next[prev]; next[prev] = TradeExecutor(0); } next[address(0)] = curr; // if we have remaining debt and stake, we use Uniswap // we can use uniswap by specifying desired output or input // we if (remainingDebt > 0) { if (remainingStake > 0) { if (outputForUniswapV1Input(remainingStake, outputUniswapV1State, stakeUniswapV1State) < uint256(remainingDebt)) { // liquidate all remaining stake :( uint256 outputAmount = stakeUniswapV1State.uniswap.tokenToExchangeSwapInput(remainingStake, 1, 1, block.timestamp, outputUniswapV1State.uniswap); emit Liquidated(remainingStake, outputAmount); // update remaining stake and debt remainingDebt -= int256(outputAmount); remainingStake = 0; // send output token to destination outputToken().transfer(_destination, uint256(_debt - remainingDebt)); } else { // finish liquidation via uniswap uint256 stakeSold = stakeUniswapV1State.uniswap.tokenToExchangeSwapOutput(uint256(remainingDebt), remainingStake, MAX_UINT, block.timestamp, outputUniswapV1State.uniswap); emit Liquidated(stakeSold, uint256(remainingDebt)); remainingDebt = 0; remainingStake -= stakeSold; // outputToken().transfer(_destination, uint256(_debt)); } } } else { // if we end up with a tiny amount of delta, transfer to the pool if (remainingDebt < 0) { outputToken().transfer(stakePool, uint256(-remainingDebt)); } // transfer output token to destination outputToken().transfer(_destination, uint256(_debt)); } // if there is remaining stake, return remainder to pool if (remainingStake > 0) { stakeToken().transfer(stakePool, remainingStake); } } /** * Airswap v2 logic * See 0x3E0c31C3D4067Ed5d7d294F08B79B6003B7bf9c8 * Important to prune orders which have expired * or where someone has withdrawn their capital **/ struct Order { uint256 nonce; // Unique per order and should be sequential uint256 expiry; // Expiry in seconds since 1 January 1970 Party signer; // Party to the trade that sets terms Party sender; // Party to the trade that accepts terms Party affiliate; // Party compensated for facilitating (optional) Signature signature; // Signature of the order } struct Party { bytes4 kind; // Interface ID of the token address wallet; // Wallet address of the party IERC20 token; // Contract address of the token uint256 amount; // Amount for ERC-20 or ERC-1155 uint256 id; // ID for ERC-721 or ERC-1155 } struct Signature { address signatory; // Address of the wallet used to sign address validator; // Address of the intended swap contract bytes1 version; // EIP-191 signature version uint8 v; // `v` value of an ECDSA signature bytes32 r; // `r` value of an ECDSA signature bytes32 s; // `s` value of an ECDSA signature } // if there is a hard fork, must update these gas costs bytes4 constant ERC20_KIND = 0x36372b07; uint256 constant SWAP_GAS_COST = 150000; uint256 constant PRUNE_GAS_COST = 30000; struct FlatOrder { uint256 nonce; // Unique per order and should be sequential uint256 expiry; // Expiry in seconds since 1 January 1970 bytes4 signerKind; // Interface ID of the token address signerWallet; // Wallet address of the party IERC20 signerToken; // Contract address of the token uint256 signerAmount; // Amount for ERC-20 or ERC-1155 uint256 signerId; // ID for ERC-721 or ERC-1155 bytes4 senderKind; // Interface ID of the token address senderWallet; // Wallet address of the party IERC20 senderToken; // Contract address of the token uint256 senderAmount; // Amount for ERC-20 or ERC-1155 uint256 senderId; // ID for ERC-721 or ERC-1155 bytes4 affiliateKind; // Interface ID of the token address affiliateWallet; // Wallet address of the party address affiliateToken; // Contract address of the token uint256 affiliateAmount; // Amount for ERC-20 or ERC-1155 uint256 affiliateId; // ID for ERC-721 or ERC-1155 address signatory; // Address of the wallet used to sign address validator; // Address of the intended swap contract bytes1 version; // EIP-191 signature version uint8 v; // `v` value of an ECDSA signature bytes32 r; // `r` value of an ECDSA signature bytes32 s; // `s` value of an ECDSA signature } /** * @dev Copies airswap info into memory and returns it * Uses extcodecopy * Needs to return a FlatOrder instead of an Order to save space in memory */ function airswapOrderInfo(TradeExecutor _airswapOrderContract) public view returns (FlatOrder memory order) { assembly { extcodecopy(_airswapOrderContract, order, 51, 736) } } bytes32 constant ORDER_TYPEHASH = 0x1b7987701aec5d914b7e2663640474d587fdf71bf8cf50a672b29ff7ddc7b557; bytes32 constant PARTY_TYPEHASH = 0xf7dd27dc10c7dbaecb34f7bf8396d9ce2f7972a5556959ec094912041b15e285; //bytes32 constant DOMAIN_TYPEHASH = 0x91ab3d17e3a50a9d89e63fd30b92be7f5336b03b287bb946787a83a9d62a2766; bytes32 constant ZERO_PARTY_HASH = 0xb3df6f92b1402b8652ec14dde0ab8816789b2da8a6b0962109a31f4c72c625d2; /** * @dev Calculate signature for airswap */ function hashERC20Party(Party memory _party) internal pure returns (bytes32) { return keccak256(abi.encode(PARTY_TYPEHASH, ERC20_KIND, _party.wallet, _party.token, _party.amount, _party.id)); } /** * @dev Return true if valid airswap signatory * Can sign on someone else's behalf if authorized */ function validAirswapSignatory(Swap validator, address signer, address signatory) internal view returns (bool) { if (signatory == signer) { return true; } return validator.signerAuthorizations(signer, signatory); } /** * @dev Return true if valid airswap signature */ function validAirswapSignature(Order memory _order) internal view returns (bool) { bytes32 hash = keccak256(abi.encodePacked(EIP191_HEADER, domainSeparators[_order.signature.validator], keccak256(abi.encode(ORDER_TYPEHASH, _order.nonce, _order.expiry, hashERC20Party(_order.signer), hashERC20Party(_order.sender), ZERO_PARTY_HASH)))); if (_order.signature.version == 0x45) { return ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), _order.signature.v, _order.signature.r, _order.signature.s) == _order.signature.signatory; } else if (_order.signature.version == 0x01) { return ecrecover(hash, _order.signature.v, _order.signature.r, _order.signature.s) == _order.signature.signatory; } else { return false; } } /** * @dev Register Valid Airswap * Ensures a bunch of logic to regsiter a valid airswap order * Prevent really large orders that would cause overflow * Ensures correct exchange of token types * Ensures no affiliate in airswap order * Checks signer has the balance they are offering to exchange * Checks order registrant has approval * * Downsides: * Can register orders that fail, but this will be pruned very cheaply * Can register order and transfer in the same transaction */ function registerAirswap(Order calldata _order) external returns (TradeExecutor orderContract) { require(domainSeparators[_order.signature.validator] != bytes32(0), "unregistered validator"); require(_order.expiry > now + 1 hours, "expiry too soon"); require(_order.sender.kind == ERC20_KIND, "send erc20"); require(_order.sender.wallet == address(this), "counterparty must be liquidator"); require(_order.sender.amount < MAX_UINT128, "ask too large"); require(_order.sender.token == stakeToken(), "must buy stake"); require(_order.signer.kind == ERC20_KIND, "sign erc20"); require(_order.signer.token == outputToken(), "incorrect token offerred"); require(_order.signer.amount < MAX_UINT128, "bid too large"); require(_order.affiliate.amount == 0, "affiliate amount must be zero"); require(_order.affiliate.wallet == address(0), "affiliate wallet must be zero"); require(_order.affiliate.kind == ERC20_KIND, "affiliate erc20"); require(outputToken().balanceOf(_order.signer.wallet) >= _order.signer.amount, "insufficient signer balance"); require(outputToken().allowance(_order.signer.wallet, _order.signature.validator) >= _order.signer.amount, "insufficient signer allowance"); uint256 poolBalance = stakeToken().balanceOf(pool()); require(poolBalance >= _order.sender.amount, "insufficient pool balance"); // verify senderAmount / poolBalance > swapGasCost / blockGasLimit require(_order.sender.amount.mul(block.gaslimit, "senderAmount overflow") > poolBalance.mul(SWAP_GAS_COST, "poolBalance overflow"), "order too small"); Swap validator = Swap(_order.signature.validator); // check nonce data require(validator.signerMinimumNonce(_order.signer.wallet) <= _order.nonce, "signer minimum nonce is higher"); require(validator.signerNonceStatus(_order.signer.wallet, _order.nonce) == AIRSWAP_AVAILABLE, "signer nonce unavailable"); // validate signature and signatory require(validAirswapSignature(_order), "signature invalid"); require(validAirswapSignatory(Swap(_order.signature.validator), _order.signer.wallet, _order.signature.signatory), "signatory invalid"); /* Create an order contract with the bytecode to call the validator with the supplied args During execution this liquidator will delegatecall into the order contract The order contract copies its code to memory to load the calldata and then executes call The order contract returns the data from the validator Though the return data is expected to be empty, we will still report whether the contract reverted, by reverting if it reverts We do not need to worry about other contexts executing this contract because we check that the liquidator is the counterparty and the liquidator will authorize no spenders Deploy (10 bytes) PC Opcodes Assembly Stack 00 610313 PUSH2 0313 787 03 80 DUP1 787 787 04 600A PUSH1 0A 787 787 10 06 3D RETURNDATASIZE 787 787 10 0 07 39 CODECOPY 787 08 3D RETURNDATASIZE 787 0 09 F3 RETURN Order Contract (787 bytes) PC Opcodes Assembly Stack Notes 00 38 CODESIZE cs 01 3D RETURNDATASIZE cs 0 02 3D RETURNDATASIZE cs 0 0 03 39 CODECOPY 04 38 CODESIZE 0 (outSize) 05 3D RETURNDATASIZE 0 0 (outStart) 06 6102E4 PUSH2 2E4 0 0 740 (inSize) 09 602F PUSH1 2F 0 0 740 2F (inStart) 0b 3D RETURNDATASIZE 0 0 740 2F 0 wei 0c 73xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx PUSH20 validator 0 0 740 2F 0 validator address (maybe use mload?) 21 5A GAS 0 0 740 2F 0 validator gas 22 F1 CALL success 23 602A PUSH1 2A success goto 25 57 JUMPI 26 3D RETURNDATASIZE rds 27 6000 PUSH1 0 rds 0 29 FD REVERT 2a 5B JUMPDEST 2b 3D RETURNDATASIZE rds 2c 6000 PUSH1 0 rds 0 2e F3 RETURN 2f 67641C2F<> <Order Calldata> size of Order calldata is 740 bytes */ // above codes refer to the assembly below assembly { let start := mload(0x40) mstore(start, 0x00000000000000000000000000000000000000000061031380600A3D393DF338) mstore(add(start, 32), or(0x3D3D39383D6102E4602F3D730000000000000000000000000000000000000000, validator)) mstore(add(start, 64), 0x5AF1602A573D6000FD5B3D6000F367641C2F0000000000000000000000000000) calldatacopy(add(start, 82), 4, 736) orderContract := create(0, add(start, 21), 797) } // walk through list and insert order // if we run out of gas we revert // e.g. if someone's order isn't good enough to be address prev = address(0); TradeExecutor curr = next[address(0)]; while (curr != TradeExecutor(0)) { FlatOrder memory currInfo = airswapOrderInfo(curr); // no need to check overflow because multiplying unsigned values under 16 bytes results in an unsigned value under 32 bytes if (currInfo.signerAmount * _order.sender.amount < currInfo.senderAmount * _order.signer.amount) { next[address(orderContract)] = curr; break; } poolBalance -= currInfo.senderAmount; prev = address(curr); curr = next[prev]; } require(poolBalance >= _order.sender.amount, "insufficent remaining pool balance"); next[prev] = orderContract; emit LimitOrder(orderContract); return orderContract; } /** * @dev return True if an order is prunable * If the order cannot be executed at this moment, it is prunable * No need to check things immutably true that were checked during registration */ function prunableOrder(FlatOrder memory _order) internal view returns (bool) { if (_order.expiry < now) { return true; } // can assume rewardToken == outputToken() IERC20 rewardToken = _order.signerToken; if (rewardToken.balanceOf(_order.signerWallet) < _order.signerAmount) { return true; } // check allowance, nonce status, and minimum nonce correspond to cancellation if (rewardToken.allowance(_order.signerWallet, _order.validator) < _order.signerAmount) { return true; } if (Swap(_order.validator).signerNonceStatus(_order.signerWallet, _order.nonce) != AIRSWAP_AVAILABLE) { return true; } if (Swap(_order.validator).signerMinimumNonce(_order.signerWallet) > _order.nonce) { return true; } // check signatory has not been revoked if (!validAirswapSignatory(Swap(_order.validator), _order.signerWallet, _order.signatory)) { return true; } return false; } /** * @dev Remove all orders that would fail * Remove all orders worse than what is available in uniswap * Much cheaper to prune than to run an order that would fail */ function prune() external { address prevValid = address(0); TradeExecutor curr = next[address(0)]; // walk through list and prune while (curr != TradeExecutor(0) && gasleft() > PRUNE_GAS_COST) { // get order from memory FlatOrder memory currInfo = airswapOrderInfo(curr); // if order is prunable, remove from linkedlist // otherwise continue to walk through list // gas refud from pruning makes it very cheap if (prunableOrder(currInfo)) { emit Cancel(curr); address prev = address(curr); curr = next[prev]; next[prev] = TradeExecutor(0); } else { if (next[prevValid] != curr) { next[prevValid] = curr; } prevValid = address(curr); curr = next[prevValid]; } } next[prevValid] = curr; } }
Calculate how much output we get for a stake input amount Much cheaper to do this logic ourselves locally than an external call Allows us to do this multiple times in one transaction See ./uniswap/uniswap_exchange.vy/
function outputForUniswapV1Input(uint256 stakeInputAmount, UniswapState memory outputUniswapV1State, UniswapState memory stakeUniswapV1State) internal pure returns (uint256 outputAmount) { uint256 inputAmountWithFee = 997 * stakeInputAmount; inputAmountWithFee = 997 * (inputAmountWithFee * stakeUniswapV1State.etherBalance) / (stakeUniswapV1State.tokenBalance * 1000 + inputAmountWithFee); outputAmount = (inputAmountWithFee * outputUniswapV1State.tokenBalance) / (outputUniswapV1State.etherBalance * 1000 + inputAmountWithFee); }
5,408,644
pragma solidity ^0.5.8; import "./Owned.sol"; import "./BirthDate.sol"; contract MarketPlace is Owned { //structure of farmer - buyer/seller struct Farmer { uint aadhaar; // aadhar id of the farmer address farmer_address; // blockchain identifier of the farmer string name; string residence_address; string email; string phone; } //structure of cattle struct Cattle { uint cattle_id; // unique id of the cattle address cattle_address; // blockchain identifier of the cattle address owner; string name; uint age; string breed; uint lastCalfBirth; bool isCow; uint milkInLiters; string health; string description; } //structure of dairy_company struct Dairy_Company { uint dairy_id; // unique id of the dairy_company address dairy_company_address; // blockchain identifier of the dairy_company string name; string residence_address; string email; string phone; string description; } //structure of Veterinarian struct Veterinarian { uint veterinarians_id; // unique id of the Veterinarian address veterinarians_address; // blockchain identifier of the Veterinarian string name; string residence_address; string email; string phone; string description; } // Global Veriables uint nFarmers; uint nCowsPerFarmer; uint nDaires; uint nVeterinarian; uint cattleCounter = 0; uint dairyCounter = 0; uint veterinarianCounter = 0; // address to borrower map mapping (address => Farmer) public cattle_to_owner_map; mapping (address => uint) public seller_rating_map; mapping(uint => Cattle) public cattles_for_sell_map; uint cattlesForSellCount; address[2] dummyFarmers = [0x02e292B88FAF7ca8118b66956faf418724bC3B30, 0x86F6d73036673B379b2b97e6b02f6B100815C7fA]; address[6] dummyCattles = [0xfC8CDa1B389223fA8b827687Cd4124C6F2936a7D, 0xF03Bf8432548F49B2782dE4A4a37D1BCb7115557, 0x2FcB336F47dfc35bB68cF595F1C352Fab47E701e, 0x58536970581B2D7D0D789fD4b7297e7D18aDe90E, 0x53ea6c69BD5d0906c226e9Cba5b7D4177656FA06, 0xbd588caC001Ef83e5ddd3021647d5041B19202f5]; address dummyDairy = 0x0C07945aC6f20B409248CDBBffac32265e71a444; address dummyVeterinarian = 0x2CD001b47Abd5bB9BBfd8d01f30F0B76917Fa496; //Events event sellCattleEvent( uint indexed _id, address indexed _seller, string _name, uint256 _price); event sellMilkEvent( uint indexed _id, address indexed _seller, string _name, uint256 _price); event buyCattleEvent( uint indexed _id, address indexed _seller, address indexed _buyer, string _name, uint256 _price); Farmer[] Farmers;// = new Farmer[](nFarmers); Cattle[] Cattles;// = new Cattle[](nCowsPerFarmer); Dairy_Company[] Dairy_Companies;// = new Dairy_Company[](nDaires); Veterinarian[] Veterinarians;// = new Veterinarian[](nVeterinarian); constructor() public { } /*constructor(uint _n_farmers, uint _n_cowsperfarmer, uint _n_daires, uint _n_veterinarian) public { nFarmers = _n_farmers; nCowsPerFarmer = _n_cowsperfarmer; nDaires = _n_daires; nVeterinarian = _n_veterinarian; }*/ function registerAccount (uint _accountType, string memory _name, string memory _emailId, string memory _resAddress, string memory _phone, string memory _password1, uint _identity) public { require(_identity != 0, "Invalid identity number!"); if (_accountType == 1) // Farmer { //for (uint i = 0; i < Farmers.length; i++) //{ // require(Farmers[i].farmer_address != _new_farmer, "Farmer already added into the network!"); //} Farmers.push(Farmer({ aadhaar: _identity, farmer_address: dummyFarmers[Farmers.length % (dummyFarmers.length - 1)], name: _name, residence_address: _resAddress, email: _emailId, phone: _phone })); } else if (_accountType == 2) // Veterinarian { //for (uint i = 0; i < Veterinarians.length; i++) //{ // require(Veterinarians[i].veterinarians_address != _new_veterinarian, "Veterinarian already added into the network!"); //} Veterinarians.push(Veterinarian({ veterinarians_id: ++veterinarianCounter, // unique id of the Veterinarian veterinarians_address: dummyVeterinarian, // blockchain identifier of the Veterinarian name: _name, residence_address: _resAddress, email: _emailId, phone: _phone, description: "" })); } else if (_accountType == 3) // Dairy Company { //for (uint i = 0; i < Dairy_Companies.length; i++) //{ // //require(Dairy_Companies[i].dairy_company_address != _new_dairy, "Dairy already added into the network!"); //} Dairy_Companies.push(Dairy_Company({ dairy_id: ++dairyCounter, // unique id of the dairy_company dairy_company_address: dummyDairy, // blockchain identifier of the dairy_company name: _name, residence_address: _resAddress, email: _emailId, phone: _phone, description: "" })); } } // ====================== Farmer (buyer or seller) Functions Start ====================== function RegisterFarmer(address _new_farmer, string memory _name, string memory _res_address, string memory _email, string memory _phone, uint _aadhaar, bool _asSeller/*?*/) public { require(_aadhaar != 0, "Invalid aadhaar number!"); for (uint i = 0; i < Farmers.length; i++) { require(Farmers[i].farmer_address != _new_farmer, "Farmer already added into the network!"); } Farmers.push(Farmer({ aadhaar: _aadhaar, farmer_address: _new_farmer, name: _name, residence_address: _res_address, email: _email, phone: _phone })); } function UnRegisterFarmer(address farmer) public { //- self unregistration for (uint i = 0; i < Farmers.length; i++) { if (Farmers[i].farmer_address == farmer) { delete Farmers[i]; break; } } } function SetBasePriceForCattle(address cattle, uint baseprice) public { //- farmer should be the owner of the cattle } function StartAuctionForCattle(address cattle, uint acutionperiod) public { // - farmer should be the owner of the cattle } function EndAuctionForCattle(address cattle) public { // - farmer should be the owner of the cattle, - the ownership of the cattle has to be transferred } function SetBasePriceFoCowMilk(address cattle, uint baseprice) public { // - baseprice - per liter, - farmer should be the owner of the cattle } function StartAuctionForCowMilk(address cattle, uint acutionperiod, uint milkInLiters) public { // auctionperiod is in mins // - total price = baseprice * milkInLiters, - farmer should be the owner of the cattle } function EndAuctionForCowMilk(address cattle) public { // - farmer should be the owner of the cattle, the ownership of the cow milk has to be transferred } function RegisterCattle(string memory _name, uint _age, string memory _breed, uint _lastCalfBirth, bool _isCow, uint _milkInLiters/*?*/, string memory _health/*?*/, string memory _description) public { // - owner should be registered before hand into the system, - health last updated, - get health confirmation from the veterinarians //for (uint i = 0; i < Cattles.length; i++) //{ // require(Cattles[i].cattle_address != _new_cattle, "Cattle already added into the network!"); //} Cattles.push(Cattle({ cattle_id: ++cattleCounter, // unique id of the cattle cattle_address: dummyCattles[Cattles.length % (dummyCattles.length - 1)], // blockchain identifier of the cattle owner:msg.sender, name: _name, age: _age, breed: _breed, lastCalfBirth: _lastCalfBirth, isCow: _isCow, milkInLiters: _milkInLiters, health: _health, description: _description })); // Fillup the cattle ownership map for (uint i = 0; i < Farmers.length; i++) { if (Farmers[i].farmer_address == msg.sender) { cattle_to_owner_map[dummyCattles[Cattles.length % (dummyCattles.length - 1)]] = Farmers[i]; // This Farmer is the owner of the cattle break; } } } function RequestHealthConfirmation(uint vid, address cattle, string memory health) public { // - get health confirmation from the veterinarians } function HealthConfirmed(address cattle) public { // - event raised by Veterinarians } function UpdateCattleHealth(/*?*/) public { // - health certificate or health as - good, not-good, better, best?, - get health confirmation from the veterinarians } function UnRegisterCattle(address cattle) public { // - farmer should be the owner of the cattle for (uint i = 0; i < Cattles.length; i++) { if (Cattles[i].cattle_address == cattle) { require(Cattles[i].owner != msg.sender, "Farmer should be the owner of the cattle!"); delete Cattles[i]; break; } } } function PublishRequirement(address buyer, string memory breedofcow, uint ageofcow, bool milk, uint milkInLiters /*or numberofcattles if no milk*/) public { // - buyer's milk or cattle/cow requirement // ToDo: auto choose seller ChooseSeller(); } function ChooseSeller() private { // - private function, choses the seller based on the given requirements from the buyer } function RateBuyer(address buyer, uint rating) public { } function RateSeller(address seller, uint rating) public { // - Based on the past transactions and feedback from the buyer, the sellers will be given a trust score. require(rating > 5, "Rating should be within the range of 1 to 5!"); seller_rating_map[seller] = rating; } function RateDairy(address dairy, uint rating) public { } // ====================== Farmer (buyer or seller) Functions End ====================== // ====================== DairyCompany Functions Start ====================== function RegisterDairy(address _new_dairy, string memory _name, string memory _res_address, string memory _email, string memory _phone, string memory _description) public { for (uint i = 0; i < Dairy_Companies.length; i++) { require(Dairy_Companies[i].dairy_company_address != _new_dairy, "Dairy already added into the network!"); } Dairy_Companies.push(Dairy_Company({ dairy_id: ++dairyCounter, // unique id of the dairy_company dairy_company_address: _new_dairy, // blockchain identifier of the dairy_company name: _name, residence_address: _res_address, email: _email, phone: _phone, description: _description })); } function SetPriceForCattle(address cattle, uint price) public { // - criteria - acution should be in progress for that particular cattle. } function UnRegisterDairy(address dairy) public { for (uint i = 0; i < Dairy_Companies.length; i++) { if (Dairy_Companies[i].dairy_company_address == dairy) { delete Dairy_Companies[i]; break; } } } // ====================== DairyCompany Functions End ====================== // ====================== Veterinarians Functions Start ====================== function RegisterVeterinarian(address _new_veterinarian, string memory _name, string memory _res_address, string memory _email, string memory _phone, string memory _description) public { // - Unique Id for (uint i = 0; i < Veterinarians.length; i++) { require(Veterinarians[i].veterinarians_address != _new_veterinarian, "Veterinarian already added into the network!"); } Veterinarians.push(Veterinarian({ veterinarians_id: ++veterinarianCounter, // unique id of the Veterinarian veterinarians_address: _new_veterinarian, // blockchain identifier of the Veterinarian name: _name, residence_address: _res_address, email: _email, phone: _phone, description: _description })); } function ConfirmHealth(address cattle, string memory health) public { // - raises confirm event } function GetHealthConfirmationRequests() public { } function UnRegisterVeterinarian(address veterinarian) public { for (uint i = 0; i < Veterinarians.length; i++) { if (Veterinarians[i].veterinarians_address == veterinarian) { delete Veterinarians[i]; break; } } } // ====================== Veterinarians Functions End ====================== //kill the smart contract function kill() private onlyOwner { //selfdestruct(owner); } }
- health certificate or health as - good, not-good, better, best?, - get health confirmation from the veterinarians
function UpdateCattleHealth(/*?*/) public { }
14,081,553
/** * ________ __ __ __ __ _______ __ __ __ __ * | \| \ | \ | \ | \ | \ | \ | \ | \ | \ * | $$$$$$$$ \$$ _______ ____| $$ _| $$_ | $$____ ______ | $$$$$$$\ ______ | $$____ | $$____ \$$ _| $$_ * | $$__ | \| \ / $$ | $$ \ | $$ \ / \ | $$__| $$ | \ | $$ \ | $$ \ | \| $$ \ * | $$ \ | $$| $$$$$$$\| $$$$$$$ \$$$$$$ | $$$$$$$\| $$$$$$\ | $$ $$ \$$$$$$\| $$$$$$$\| $$$$$$$\| $$ \$$$$$$ * | $$$$$ | $$| $$ | $$| $$ | $$ | $$ __ | $$ | $$| $$ $$ | $$$$$$$\ / $$| $$ | $$| $$ | $$| $$ | $$ __ * | $$ | $$| $$ | $$| $$__| $$ | $$| \| $$ | $$| $$$$$$$$ | $$ | $$| $$$$$$$| $$__/ $$| $$__/ $$| $$ | $$| \ * | $$ | $$| $$ | $$ \$$ $$ \$$ $$| $$ | $$ \$$ \ | $$ | $$ \$$ $$| $$ $$| $$ $$| $$ \$$ $$ * \$$ \$$ \$$ \$$ \$$$$$$$ \$$$$ \$$ \$$ \$$$$$$$ \$$ \$$ \$$$$$$$ \$$$$$$$ \$$$$$$$ \$$ \$$$$ * * * ╔═╗┌─┐┌─┐┬┌─┐┬┌─┐┬ ┌─────────────────────────┐ ╦ ╦┌─┐┌┐ ╔═╗┬┌┬┐┌─┐ * ║ ║├┤ ├┤ ││ │├─┤│ │https://findtherabbit.me │ ║║║├┤ ├┴┐╚═╗│ │ ├┤ * ╚═╝└ └ ┴└─┘┴┴ ┴┴─┘ └─┬─────────────────────┬─┘ ╚╩╝└─┘└─┘╚═╝┴ ┴ └─┘ */ // File: contracts/lib/SafeMath.sol pragma solidity 0.5.4; /** * @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/Messages.sol pragma solidity 0.5.4; /** * EIP712 Ethereum typed structured data hashing and signing */ contract Messages { struct AcceptGame { uint256 bet; bool isHost; address opponentAddress; bytes32 hashOfMySecret; bytes32 hashOfOpponentSecret; } struct SecretData { bytes32 salt; uint8 secret; } /** * Domain separator encoding per EIP 712. * keccak256( * "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" * ) */ bytes32 public constant EIP712_DOMAIN_TYPEHASH = 0xd87cd6ef79d4e2b95e15ce8abf732db51ec771f1ca2edccf22a46c729ac56472; /** * AcceptGame struct type encoding per EIP 712 * keccak256( * "AcceptGame(uint256 bet,bool isHost,address opponentAddress,bytes32 hashOfMySecret,bytes32 hashOfOpponentSecret)" * ) */ bytes32 private constant ACCEPTGAME_TYPEHASH = 0x5ceee84403c984fbd9fb4ebf11b09c4f28f87290116c8b7f24a3e2a89d26588f; /** * Domain separator per EIP 712 */ bytes32 public DOMAIN_SEPARATOR; /** * @notice Calculates acceptGameHash according to EIP 712. * @param _acceptGame AcceptGame instance to hash. * @return bytes32 EIP 712 hash of _acceptGame. */ function _hash(AcceptGame memory _acceptGame) internal pure returns (bytes32) { return keccak256(abi.encode( ACCEPTGAME_TYPEHASH, _acceptGame.bet, _acceptGame.isHost, _acceptGame.opponentAddress, _acceptGame.hashOfMySecret, _acceptGame.hashOfOpponentSecret )); } /** * @notice Calculates secretHash according to EIP 712. * @param _salt Salt of the gamer. * @param _secret Secret of the gamer. */ function _hashOfSecret(bytes32 _salt, uint8 _secret) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_salt, _secret)); } /** * @return the recovered address from the signature */ function _recoverAddress( bytes32 messageHash, bytes memory signature ) internal view returns (address) { bytes32 r; bytes32 s; bytes1 v; // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := mload(add(signature, 0x60)) } bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, messageHash )); return ecrecover(digest, uint8(v), r, s); } /** * @return the address of the gamer signing the AcceptGameMessage */ function _getSignerAddress( uint256 _value, bool _isHost, address _opponentAddress, bytes32 _hashOfMySecret, bytes32 _hashOfOpponentSecret, bytes memory signature ) internal view returns (address playerAddress) { AcceptGame memory message = AcceptGame({ bet: _value, isHost: _isHost, opponentAddress: _opponentAddress, hashOfMySecret: _hashOfMySecret, hashOfOpponentSecret: _hashOfOpponentSecret }); bytes32 messageHash = _hash(message); playerAddress = _recoverAddress(messageHash, signature); } } // File: contracts/Ownable.sol pragma solidity 0.5.4; /** * @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 () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "not owner"); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to 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/Claimable.sol pragma solidity 0.5.4; /** * @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 Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner, "not pending owner"); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(_owner, pendingOwner); _owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/lib/ERC20Basic.sol pragma solidity 0.5.4; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); } // File: contracts/FindTheRabbit.sol pragma solidity 0.5.4; /** * @title FindTheRabbit * @dev Base game contract */ contract FindTheRabbit is Messages, Claimable { using SafeMath for uint256; enum GameState { Invalid, // Default value for a non-created game HostBetted, // A player, who initiated an offchain game and made a bet JoinBetted, // A player, who joined the game and made a bet Filled, // Both players made bets DisputeOpenedByHost, // Dispute is opened by the initiating player DisputeOpenedByJoin, // Dispute is opened by the joining player DisputeWonOnTimeoutByHost, // Dispute is closed on timeout and the prize was taken by the initiating player DisputeWonOnTimeoutByJoin, // Dispute is closed on timeout and the prize was taken by the joining player CanceledByHost, // The joining player has not made a bet and the game is closed by the initiating player CanceledByJoin, // The initiating player has not made a bet and the game is closed by the joining player WonByHost, // The initiating has won the game WonByJoin // The joining player has won the game } //Event is triggered after both players have placed their bets event GameCreated( address indexed host, address indexed join, uint256 indexed bet, bytes32 gameId, GameState state ); //Event is triggered after the first bet has been placed event GameOpened(bytes32 gameId, address indexed player); //Event is triggered after the game has been closed event GameCanceled(bytes32 gameId, address indexed player, address indexed opponent); /** * @dev Event triggered after after opening a dispute * @param gameId 32 byte game identifier * @param disputeOpener is a player who opened a dispute * @param defendant is a player against whom a dispute is opened */ event DisputeOpened(bytes32 gameId, address indexed disputeOpener, address indexed defendant); //Event is triggered after a dispute is resolved by the function resolveDispute() event DisputeResolved(bytes32 gameId, address indexed player); //Event is triggered after a dispute is closed after the amount of time specified in disputeTimer event DisputeClosedOnTimeout(bytes32 gameId, address indexed player); //Event is triggered after sending the winning to the winner event WinnerReward(address indexed winner, uint256 amount); //Event is triggered after the jackpot is sent to the winner event JackpotReward(bytes32 gameId, address player, uint256 amount); //Event is triggered after changing the gameId that claims the jackpot event CurrentJackpotGame(bytes32 gameId); //Event is triggered after sending the reward to the referrer event ReferredReward(address referrer, uint256 amount); // Emitted when calimTokens function is invoked. event ClaimedTokens(address token, address owner, uint256 amount); //The address of the contract that will verify the signature per EIP 712. //In this case, the current address of the contract. address public verifyingContract = address(this); //An disambiguating salt for the protocol per EIP 712. //Set through the constructor. bytes32 public salt; //An address of the creators' account receiving the percentage of Commission for the game address payable public teamWallet; //Percentage of commission from the game that is sent to the creators uint256 public commissionPercent; //Percentage of reward to the player who invited new players //0.1% is equal 1 //0.5% is equal 5 //1% is equal 10 //10% is equal 100 uint256 public referralPercent; //Maximum allowed value of the referralPercent. (10% = 100) uint256 public maxReferralPercent = 100; //Minimum bet value to create a new game uint256 public minBet = 0.01 ether; //Percentage of game commission added to the jackpot value uint256 public jackpotPercent; //Jackpot draw time in UNIX time stamp format. uint256 public jackpotDrawTime; //Current jackpot value uint256 public jackpotValue; //The current value of the gameId of the applicant for the jackpot. bytes32 public jackpotGameId; //Number of seconds added to jackpotDrawTime each time a new game is added to the jackpot. uint256 public jackpotGameTimerAddition; //Initial timeout for a new jackpot round. uint256 public jackpotAccumulationTimer; //Timeout in seconds during which the dispute cannot be opened. uint256 public revealTimer; //Maximum allowed value of the minRevealTimer in seconds. uint256 public maxRevealTimer; //Minimum allowed value of the minRevealTimer in seconds. uint256 public minRevealTimer; //Timeout in seconds during which the dispute cannot be closed //and players can call the functions win() and resolveDispute(). uint256 public disputeTimer; //Maximum allowed value of the maxDisputeTimer in seconds. uint256 public maxDisputeTimer; //Minimum allowed value of the minDisputeTimer in seconds. uint256 public minDisputeTimer; //Timeout in seconds after the first bet //during which the second player's bet is expected //and the game cannot be closed. uint256 public waitingBetTimer; //Maximum allowed value of the waitingBetTimer in seconds. uint256 public maxWaitingBetTimer; //Minimum allowed value of the waitingBetTimer in seconds. uint256 public minWaitingBetTimer; //The time during which the game must be completed to qualify for the jackpot. uint256 public gameDurationForJackpot; uint256 public chainId; //Mapping for storing information about all games mapping(bytes32 => Game) public games; //Mapping for storing information about all disputes mapping(bytes32 => Dispute) public disputes; //Mapping for storing information about all players mapping(address => Statistics) public players; struct Game { uint256 bet; // bet value for the game address payable host; // address of the initiating player address payable join; // address of the joining player uint256 creationTime; // the time of the last bet in the game. GameState state; // current state of the game bytes hostSignature; // the value of the initiating player's signature bytes joinSignature; // the value of the joining player's signature bytes32 gameId; // 32 byte game identifier } struct Dispute { address payable disputeOpener; // address of the player, who opened the dispute. uint256 creationTime; // dispute opening time of the dispute. bytes32 opponentHash; // hash from an opponent's secret and salt uint256 secret; // secret value of the player, who opened the dispute bytes32 salt; // salt value of the player, who opened the dispute bool isHost; // true if the player initiated the game. } struct Statistics { uint256 totalGames; // totalGames played by the player uint256 totalUnrevealedGames; // total games that have been disputed against a player for unrevealing the secret on time uint256 totalNotFundedGames; // total number of games a player has not send funds on time uint256 totalOpenedDisputes; // total number of disputed games created by a player against someone for unrevealing the secret on time uint256 avgBetAmount; // average bet value } /** * @dev Throws if the game state is not Filled. */ modifier isFilled(bytes32 _gameId) { require(games[_gameId].state == GameState.Filled, "game state is not Filled"); _; } /** * @dev Throws if the game is not Filled or dispute has not been opened. */ modifier verifyGameState(bytes32 _gameId) { require( games[_gameId].state == GameState.DisputeOpenedByHost || games[_gameId].state == GameState.DisputeOpenedByJoin || games[_gameId].state == GameState.Filled, "game state are not Filled or OpenedDispute" ); _; } /** * @dev Throws if at least one player has not made a bet. */ modifier isOpen(bytes32 _gameId) { require( games[_gameId].state == GameState.HostBetted || games[_gameId].state == GameState.JoinBetted, "game state is not Open"); _; } /** * @dev Throws if called by any account other than the participant's one in this game. */ modifier onlyParticipant(bytes32 _gameId) { require( games[_gameId].host == msg.sender || games[_gameId].join == msg.sender, "you are not a participant of this game" ); _; } /** * @dev Setting the parameters of the contract. * Description of the main parameters can be found above. * @param _chainId Id of the current chain. * @param _maxValueOfTimer maximum value for revealTimer, disputeTimer and waitingBetTimer. * Minimum values are set with revealTimer, disputeTimer, and waitingBetTimer values passed to the constructor. */ constructor ( uint256 _chainId, address payable _teamWallet, uint256 _commissionPercent, uint256 _jackpotPercent, uint256 _referralPercent, uint256 _jackpotGameTimerAddition, uint256 _jackpotAccumulationTimer, uint256 _revealTimer, uint256 _disputeTimer, uint256 _waitingBetTimer, uint256 _gameDurationForJackpot, bytes32 _salt, uint256 _maxValueOfTimer ) public { teamWallet = _teamWallet; jackpotDrawTime = getTime().add(_jackpotAccumulationTimer); jackpotAccumulationTimer = _jackpotAccumulationTimer; commissionPercent = _commissionPercent; jackpotPercent = _jackpotPercent; referralPercent = _referralPercent; jackpotGameTimerAddition = _jackpotGameTimerAddition; revealTimer = _revealTimer; minRevealTimer = _revealTimer; maxRevealTimer = _maxValueOfTimer; disputeTimer = _disputeTimer; minDisputeTimer = _disputeTimer; maxDisputeTimer = _maxValueOfTimer; waitingBetTimer = _waitingBetTimer; minWaitingBetTimer = _waitingBetTimer; maxWaitingBetTimer = _maxValueOfTimer; gameDurationForJackpot = _gameDurationForJackpot; salt = _salt; chainId = _chainId; DOMAIN_SEPARATOR = keccak256(abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256("Find The Rabbit"), keccak256("0.1"), _chainId, verifyingContract, salt )); } /** * @dev Change the current waitingBetTimer value. * Change can be made only within the maximum and minimum values. * @param _waitingBetTimer is a new value of waitingBetTimer */ function setWaitingBetTimerValue(uint256 _waitingBetTimer) external onlyOwner { require(_waitingBetTimer >= minWaitingBetTimer, "must be more than minWaitingBetTimer"); require(_waitingBetTimer <= maxWaitingBetTimer, "must be less than maxWaitingBetTimer"); waitingBetTimer = _waitingBetTimer; } /** * @dev Change the current disputeTimer value. * Change can be made only within the maximum and minimum values. * @param _disputeTimer is a new value of disputeTimer. */ function setDisputeTimerValue(uint256 _disputeTimer) external onlyOwner { require(_disputeTimer >= minDisputeTimer, "must be more than minDisputeTimer"); require(_disputeTimer <= maxDisputeTimer, "must be less than maxDisputeTimer"); disputeTimer = _disputeTimer; } /** * @dev Change the current revealTimer value. * Change can be made only within the maximum and minimum values. * @param _revealTimer is a new value of revealTimer */ function setRevealTimerValue(uint256 _revealTimer) external onlyOwner { require(_revealTimer >= minRevealTimer, "must be more than minRevealTimer"); require(_revealTimer <= maxRevealTimer, "must be less than maxRevealTimer"); revealTimer = _revealTimer; } /** * @dev Change the current minBet value. * @param _newValue is a new value of minBet. */ function setMinBetValue(uint256 _newValue) external onlyOwner { require(_newValue != 0, "must be greater than 0"); minBet = _newValue; } /** * @dev Change the current jackpotGameTimerAddition. * Change can be made only within the maximum and minimum values. * Jackpot should not hold significant value * @param _jackpotGameTimerAddition is a new value of jackpotGameTimerAddition */ function setJackpotGameTimerAddition(uint256 _jackpotGameTimerAddition) external onlyOwner { if (chainId == 1) { // jackpot must be less than 150 DAI. 1 ether = 150 DAI require(jackpotValue <= 1 ether); } if (chainId == 99) { // jackpot must be less than 150 DAI. 1 POA = 0.03 DAI require(jackpotValue <= 4500 ether); } require(_jackpotGameTimerAddition >= 2 minutes, "must be more than 2 minutes"); require(_jackpotGameTimerAddition <= 1 hours, "must be less than 1 hour"); jackpotGameTimerAddition = _jackpotGameTimerAddition; } /** * @dev Change the current referralPercent value. * Example: * 1 = 0.1% * 5 = 0.5% * 10 = 1% * @param _newValue is a new value of referralPercent. */ function setReferralPercentValue(uint256 _newValue) external onlyOwner { require(_newValue <= maxReferralPercent, "must be less than maxReferralPercent"); referralPercent = _newValue; } /** * @dev Change the current commissionPercent value. * Example: * 1 = 1% * @param _newValue is a new value of commissionPercent. */ function setCommissionPercent(uint256 _newValue) external onlyOwner { require(_newValue <= 20, "must be less than 20"); commissionPercent = _newValue; } /** * @dev Change the current teamWallet address. * @param _newTeamWallet is a new teamWallet address. */ function setTeamWalletAddress(address payable _newTeamWallet) external onlyOwner { require(_newTeamWallet != address(0)); teamWallet = _newTeamWallet; } /** * @return information about the jackpot. */ function getJackpotInfo() external view returns ( uint256 _jackpotDrawTime, uint256 _jackpotValue, bytes32 _jackpotGameId ) { _jackpotDrawTime = jackpotDrawTime; _jackpotValue = jackpotValue; _jackpotGameId = jackpotGameId; } /** * @return timers used for games. */ function getTimers() external view returns ( uint256 _revealTimer, uint256 _disputeTimer, uint256 _waitingBetTimer, uint256 _jackpotAccumulationTimer ) { _revealTimer = revealTimer; _disputeTimer = disputeTimer; _waitingBetTimer = waitingBetTimer; _jackpotAccumulationTimer = jackpotAccumulationTimer; } /** * @dev Transfer of tokens from the contract * @param _token the address of the tokens to be transferred. */ function claimTokens(address _token) public onlyOwner { ERC20Basic erc20token = ERC20Basic(_token); uint256 balance = erc20token.balanceOf(address(this)); erc20token.transfer(owner(), balance); emit ClaimedTokens(_token, owner(), balance); } /** * @dev Allows to create a game and place a bet. * @param _isHost True if the sending account initiated the game. * @param _hashOfMySecret Hash value of the sending account's secret and salt. * @param _hashOfOpponentSecret Hash value of the opponent account's secret and salt. * @param _hostSignature Signature of the initiating player from the following values: * bet, * isHost, // true * opponentAddress, // join address * hashOfMySecret, // hash of host secret * hashOfOpponentSecret // hash of join secret * @param _joinSignature Signature of the joining player from the following values: * bet, * isHost, // false * opponentAddress, // host address * hashOfMySecret, // hash of join secret * hashOfOpponentSecret // hash of host secret */ function createGame( bool _isHost, bytes32 _hashOfMySecret, bytes32 _hashOfOpponentSecret, bytes memory _hostSignature, bytes memory _joinSignature ) public payable { require(msg.value >= minBet, "must be greater than the minimum value"); bytes32 gameId = getGameId(_hostSignature, _joinSignature); address opponent = _getSignerAddress( msg.value, !_isHost, msg.sender, _hashOfOpponentSecret, _hashOfMySecret, _isHost ? _joinSignature : _hostSignature); require(opponent != msg.sender, "send your opponent's signature"); Game storage game = games[gameId]; if (game.gameId == 0){ _recordGameInfo(msg.value, _isHost, gameId, opponent, _hostSignature, _joinSignature); emit GameOpened(game.gameId, msg.sender); } else { require(game.host == msg.sender || game.join == msg.sender, "you are not paticipant in this game"); require(game.state == GameState.HostBetted || game.state == GameState.JoinBetted, "the game is not Opened"); if (_isHost) { require(game.host == msg.sender, "you are not the host in this game"); require(game.join == opponent, "invalid join signature"); require(game.state == GameState.JoinBetted, "you have already made a bet"); } else { require(game.join == msg.sender, "you are not the join in this game."); require(game.host == opponent, "invalid host signature"); require(game.state == GameState.HostBetted, "you have already made a bet"); } game.creationTime = getTime(); game.state = GameState.Filled; emit GameCreated(game.host, game.join, game.bet, game.gameId, game.state); } } /** * @dev If the disclosure is true, the winner gets a prize. * @notice a referrer will be sent a reward to. * only if the referrer has previously played the game and the sending account has not. * @param _gameId 32 byte game identifier. * @param _hostSecret The initiating player's secret. * @param _hostSalt The initiating player's salt. * @param _joinSecret The joining player's secret. * @param _joinSalt The joining player's salt. * @param _referrer The winning player's referrer. The referrer must have played games. */ function win( bytes32 _gameId, uint8 _hostSecret, bytes32 _hostSalt, uint8 _joinSecret, bytes32 _joinSalt, address payable _referrer ) public verifyGameState(_gameId) onlyParticipant(_gameId) { Game storage game = games[_gameId]; bytes32 hashOfHostSecret = _hashOfSecret(_hostSalt, _hostSecret); bytes32 hashOfJoinSecret = _hashOfSecret(_joinSalt, _joinSecret); address host = _getSignerAddress( game.bet, true, game.join, hashOfHostSecret, hashOfJoinSecret, game.hostSignature ); address join = _getSignerAddress( game.bet, false, game.host, hashOfJoinSecret, hashOfHostSecret, game.joinSignature ); require(host == game.host && join == game.join, "invalid reveals"); address payable winner; if (_hostSecret == _joinSecret){ winner = game.join; game.state = GameState.WonByJoin; } else { winner = game.host; game.state = GameState.WonByHost; } if (isPlayerExist(_referrer) && _referrer != msg.sender) { _processPayments(game.bet, winner, _referrer); } else { _processPayments(game.bet, winner, address(0)); } _jackpotPayoutProcessing(_gameId); _recordStatisticInfo(game.host, game.join, game.bet); } /** * @dev If during the time specified in revealTimer one of the players does not send * the secret and salt to the opponent, the player can open a dispute. * @param _gameId 32 byte game identifier * @param _secret Secret of the player, who opens the dispute. * @param _salt Salt of the player, who opens the dispute. * @param _isHost True if the sending account initiated the game. * @param _hashOfOpponentSecret The hash value of the opponent account's secret and salt. */ function openDispute( bytes32 _gameId, uint8 _secret, bytes32 _salt, bool _isHost, bytes32 _hashOfOpponentSecret ) public onlyParticipant(_gameId) { require(timeUntilOpenDispute(_gameId) == 0, "the waiting time for revealing is not over yet"); Game storage game = games[_gameId]; require(isSecretDataValid( _gameId, _secret, _salt, _isHost, _hashOfOpponentSecret ), "invalid salt or secret"); _recordDisputeInfo(_gameId, msg.sender, _hashOfOpponentSecret, _secret, _salt, _isHost); game.state = _isHost ? GameState.DisputeOpenedByHost : GameState.DisputeOpenedByJoin; address defendant = _isHost ? game.join : game.host; players[msg.sender].totalOpenedDisputes = (players[msg.sender].totalOpenedDisputes).add(1); players[defendant].totalUnrevealedGames = (players[defendant].totalUnrevealedGames).add(1); emit DisputeOpened(_gameId, msg.sender, defendant); } /** * @dev Allows the accused player to make a secret disclosure * and pick up the winnings in case of victory. * @param _gameId 32 byte game identifier. * @param _secret An accused player's secret. * @param _salt An accused player's salt. * @param _isHost True if the sending account initiated the game. * @param _hashOfOpponentSecret The hash value of the opponent account's secret and salt. */ function resolveDispute( bytes32 _gameId, uint8 _secret, bytes32 _salt, bool _isHost, bytes32 _hashOfOpponentSecret ) public returns(address payable winner) { require(isDisputeOpened(_gameId), "there is no dispute"); Game storage game = games[_gameId]; Dispute memory dispute = disputes[_gameId]; require(msg.sender != dispute.disputeOpener, "only for the opponent"); require(isSecretDataValid( _gameId, _secret, _salt, _isHost, _hashOfOpponentSecret ), "invalid salt or secret"); if (_secret == dispute.secret) { winner = game.join; game.state = GameState.WonByJoin; } else { winner = game.host; game.state = GameState.WonByHost; } _processPayments(game.bet, winner, address(0)); _jackpotPayoutProcessing(_gameId); _recordStatisticInfo(game.host, game.join, game.bet); emit DisputeResolved(_gameId, msg.sender); } /** * @dev If during the time specified in disputeTimer the accused player does not manage to resolve a dispute * the player, who has opened the dispute, can close the dispute and get the win. * @param _gameId 32 byte game identifier. * @return address of the winning player. */ function closeDisputeOnTimeout(bytes32 _gameId) public returns (address payable winner) { Game storage game = games[_gameId]; Dispute memory dispute = disputes[_gameId]; require(timeUntilCloseDispute(_gameId) == 0, "the time has not yet come out"); winner = dispute.disputeOpener; game.state = (winner == game.host) ? GameState.DisputeWonOnTimeoutByHost : GameState.DisputeWonOnTimeoutByJoin; _processPayments(game.bet, winner, address(0)); _jackpotPayoutProcessing(_gameId); _recordStatisticInfo(game.host, game.join, game.bet); emit DisputeClosedOnTimeout(_gameId, msg.sender); } /** * @dev If one of the player made a bet and during the time specified in waitingBetTimer * the opponent does not make a bet too, the player can take his bet back. * @param _gameId 32 byte game identifier. */ function cancelGame( bytes32 _gameId ) public onlyParticipant(_gameId) { require(timeUntilCancel(_gameId) == 0, "the waiting time for the second player's bet is not over yet"); Game storage game = games[_gameId]; address payable recipient; recipient = game.state == GameState.HostBetted ? game.host : game.join; address defendant = game.state == GameState.HostBetted ? game.join : game.host; game.state = (recipient == game.host) ? GameState.CanceledByHost : GameState.CanceledByJoin; recipient.transfer(game.bet); players[defendant].totalNotFundedGames = (players[defendant].totalNotFundedGames).add(1); emit GameCanceled(_gameId, msg.sender, defendant); } /** * @dev Jackpot draw if the time has come and there is a winner. */ function drawJackpot() public { require(isJackpotAvailable(), "is not avaliable yet"); require(jackpotGameId != 0, "no game to claim on the jackpot"); require(jackpotValue != 0, "jackpot's empty"); _payoutJackpot(); } /** * @return true if there is open dispute for given `_gameId` */ function isDisputeOpened(bytes32 _gameId) public view returns(bool) { return ( games[_gameId].state == GameState.DisputeOpenedByHost || games[_gameId].state == GameState.DisputeOpenedByJoin ); } /** * @return true if a player played at least one game and did not Cancel it. */ function isPlayerExist(address _player) public view returns (bool) { return players[_player].totalGames != 0; } /** * @return the time after which a player can close the game. * @param _gameId 32 byte game identifier. */ function timeUntilCancel( bytes32 _gameId ) public view isOpen(_gameId) returns (uint256 remainingTime) { uint256 timePassed = getTime().sub(games[_gameId].creationTime); if (waitingBetTimer > timePassed) { return waitingBetTimer.sub(timePassed); } else { return 0; } } /** * @return the time after which a player can open the dispute. * @param _gameId 32 byte game identifier. */ function timeUntilOpenDispute( bytes32 _gameId ) public view isFilled(_gameId) returns (uint256 remainingTime) { uint256 timePassed = getTime().sub(games[_gameId].creationTime); if (revealTimer > timePassed) { return revealTimer.sub(timePassed); } else { return 0; } } /** * @return the time after which a player can close the dispute opened by him. * @param _gameId 32 byte game identifier. */ function timeUntilCloseDispute( bytes32 _gameId ) public view returns (uint256 remainingTime) { require(isDisputeOpened(_gameId), "there is no open dispute"); uint256 timePassed = getTime().sub(disputes[_gameId].creationTime); if (disputeTimer > timePassed) { return disputeTimer.sub(timePassed); } else { return 0; } } /** * @return the current time in UNIX timestamp format. */ function getTime() public view returns(uint) { return block.timestamp; } /** * @return the current game state. * @param _gameId 32 byte game identifier */ function getGameState(bytes32 _gameId) public view returns(GameState) { return games[_gameId].state; } /** * @return true if the sent secret and salt match the genuine ones. * @param _gameId 32 byte game identifier. * @param _secret A player's secret. * @param _salt A player's salt. * @param _isHost True if the sending account initiated the game. * @param _hashOfOpponentSecret The hash value of the opponent account's secret and salt. */ function isSecretDataValid( bytes32 _gameId, uint8 _secret, bytes32 _salt, bool _isHost, bytes32 _hashOfOpponentSecret ) public view returns (bool) { Game memory game = games[_gameId]; bytes32 hashOfPlayerSecret = _hashOfSecret(_salt, _secret); address player = _getSignerAddress( game.bet, _isHost, _isHost ? game.join : game.host, hashOfPlayerSecret, _hashOfOpponentSecret, _isHost ? game.hostSignature : game.joinSignature ); require(msg.sender == player, "the received address does not match with msg.sender"); if (_isHost) { return player == game.host; } else { return player == game.join; } } /** * @return true if the jackpotDrawTime has come. */ function isJackpotAvailable() public view returns (bool) { return getTime() >= jackpotDrawTime; } function isGameAllowedForJackpot(bytes32 _gameId) public view returns (bool) { return getTime() - games[_gameId].creationTime < gameDurationForJackpot; } /** * @return an array of statuses for the listed games. * @param _games array of games identifier. */ function getGamesStates(bytes32[] memory _games) public view returns(GameState[] memory) { GameState[] memory _states = new GameState[](_games.length); for (uint i=0; i<_games.length; i++) { Game storage game = games[_games[i]]; _states[i] = game.state; } return _states; } /** * @return an array of Statistics for the listed players. * @param _players array of players' addresses. */ function getPlayersStatistic(address[] memory _players) public view returns(uint[] memory) { uint[] memory _statistics = new uint[](_players.length * 5); for (uint i=0; i<_players.length; i++) { Statistics storage player = players[_players[i]]; _statistics[5*i + 0] = player.totalGames; _statistics[5*i + 1] = player.totalUnrevealedGames; _statistics[5*i + 2] = player.totalNotFundedGames; _statistics[5*i + 3] = player.totalOpenedDisputes; _statistics[5*i + 4] = player.avgBetAmount; } return _statistics; } /** * @return GameId generated for current values of the signatures. * @param _signatureHost Signature of the initiating player. * @param _signatureJoin Signature of the joining player. */ function getGameId(bytes memory _signatureHost, bytes memory _signatureJoin) public pure returns (bytes32) { return keccak256(abi.encodePacked(_signatureHost, _signatureJoin)); } /** * @dev jackpot draw. */ function _payoutJackpot() internal { Game storage jackpotGame = games[jackpotGameId]; uint256 reward = jackpotValue.div(2); jackpotValue = 0; jackpotGameId = 0; jackpotDrawTime = (getTime()).add(jackpotAccumulationTimer); if (jackpotGame.host.send(reward)) { emit JackpotReward(jackpotGame.gameId, jackpotGame.host, reward.mul(2)); } if (jackpotGame.join.send(reward)) { emit JackpotReward(jackpotGame.gameId, jackpotGame.join, reward.mul(2)); } } /** * @dev adds the completed game to the jackpot draw. * @param _gameId 32 byte game identifier. */ function _addGameToJackpot(bytes32 _gameId) internal { jackpotDrawTime = jackpotDrawTime.add(jackpotGameTimerAddition); jackpotGameId = _gameId; emit CurrentJackpotGame(_gameId); } /** * @dev update jackpot info. * @param _gameId 32 byte game identifier. */ function _jackpotPayoutProcessing(bytes32 _gameId) internal { if (isJackpotAvailable()) { if (jackpotGameId != 0 && jackpotValue != 0) { _payoutJackpot(); } else { jackpotDrawTime = (getTime()).add(jackpotAccumulationTimer); } } if (isGameAllowedForJackpot(_gameId)) { _addGameToJackpot(_gameId); } } /** * @dev take a commission to the creators, reward to referrer, and commission for the jackpot from the winning amount. * Sending prize to winner. * @param _bet bet in the current game. * @param _winner the winner's address. * @param _referrer the referrer's address. */ function _processPayments(uint256 _bet, address payable _winner, address payable _referrer) internal { uint256 doubleBet = (_bet).mul(2); uint256 commission = (doubleBet.mul(commissionPercent)).div(100); uint256 jackpotPart = (doubleBet.mul(jackpotPercent)).div(100); uint256 winnerStake; if (_referrer != address(0) && referralPercent != 0 ) { uint256 referrerPart = (doubleBet.mul(referralPercent)).div(1000); winnerStake = doubleBet.sub(commission).sub(jackpotPart).sub(referrerPart); if (_referrer.send(referrerPart)) { emit ReferredReward(_referrer, referrerPart); } } else { winnerStake = doubleBet.sub(commission).sub(jackpotPart); } jackpotValue = jackpotValue.add(jackpotPart); _winner.transfer(winnerStake); teamWallet.transfer(commission); emit WinnerReward(_winner, winnerStake); } /** * @dev filling in the "Game" structure. */ function _recordGameInfo( uint256 _value, bool _isHost, bytes32 _gameId, address _opponent, bytes memory _hostSignature, bytes memory _joinSignature ) internal { Game memory _game = Game({ bet: _value, host: _isHost ? msg.sender : address(uint160(_opponent)), join: _isHost ? address(uint160(_opponent)) : msg.sender, creationTime: getTime(), state: _isHost ? GameState.HostBetted : GameState.JoinBetted , gameId: _gameId, hostSignature: _hostSignature, joinSignature: _joinSignature }); games[_gameId] = _game; } /** * @dev filling in the "Dispute" structure. */ function _recordDisputeInfo( bytes32 _gameId, address payable _disputeOpener, bytes32 _hashOfOpponentSecret, uint8 _secret, bytes32 _salt, bool _isHost ) internal { Dispute memory _dispute = Dispute({ disputeOpener: _disputeOpener, creationTime: getTime(), opponentHash: _hashOfOpponentSecret, secret: _secret, salt: _salt, isHost: _isHost }); disputes[_gameId] = _dispute; } /** * @dev filling in the "Statistics" structure. */ function _recordStatisticInfo(address _host, address _join, uint256 _bet) internal { Statistics storage statHost = players[_host]; Statistics storage statJoin = players[_join]; statHost.avgBetAmount = _calculateAvgBet(_host, _bet); statJoin.avgBetAmount = _calculateAvgBet(_join, _bet); statHost.totalGames = (statHost.totalGames).add(1); statJoin.totalGames = (statJoin.totalGames).add(1); } /** * @dev recalculation of an average bet value for a player. * @param _player the address of the player. * @param _bet bet from the last played game. */ function _calculateAvgBet(address _player, uint256 _bet) internal view returns (uint256 newAvgBetValue){ Statistics storage statistics = players[_player]; uint256 totalBets = (statistics.avgBetAmount).mul(statistics.totalGames).add(_bet); newAvgBetValue = totalBets.div(statistics.totalGames.add(1)); } }
return the address of the gamer signing the AcceptGameMessage/
function _getSignerAddress( uint256 _value, bool _isHost, address _opponentAddress, bytes32 _hashOfMySecret, bytes32 _hashOfOpponentSecret, bytes memory signature ) internal view returns (address playerAddress) { AcceptGame memory message = AcceptGame({ bet: _value, isHost: _isHost, opponentAddress: _opponentAddress, hashOfMySecret: _hashOfMySecret, hashOfOpponentSecret: _hashOfOpponentSecret }); bytes32 messageHash = _hash(message); playerAddress = _recoverAddress(messageHash, signature); }
13,000,624
./full_match/1/0xBf2A7863e2Ca59291606F47756BBa16f43e9d8aC/sources/contracts/Furnace.sol
Underlying transfer functions go here Do taxes Burn tokens Only sell tokens on a sell, as we can't interfere on a buy Swap a max of totalTokens/taxSwapDivisor, or the current balance
function _tokenTransfer( address sender, address recipient, uint256 amount, uint32 _taxAmt, uint32 _burnAmt, bool isSell ) private { uint256 receiverAmount = amount; if (_taxAmt > 0) { uint256 taxAmount = calculateTaxesFee(amount, _taxAmt); receiverAmount = amount - taxAmount; addTokens(address(this), taxAmount); emit Transfer(sender, address(this), taxAmount); } if (_burnAmt > 0) { uint256 burnAmount = calculateTaxesFee(amount, _burnAmt); receiverAmount = receiverAmount - burnAmount; addTokens(address(0x000000000000000000000000000000000000dEaD), burnAmount); emit Transfer(sender, address(0x000000000000000000000000000000000000dEaD), burnAmount); } if (isSell) { emit Sold(sender, amount); uint256 bal = balanceOf(address(this)); if (bal > 0) { if (bal > totalTokens / taxSwapDivisor) { doTaxes(totalTokens / taxSwapDivisor); doTaxes(bal); } } emit Bought(recipient, amount); } addTokens(recipient, receiverAmount); }
4,907,928
./full_match/137/0xa82cAA79F35f7d6B6f1EC1971878F3474C894565/sources/contracts/core/dao/RewardsEscrow.sol
Claim rewards for multiple escrows Uses the vaultIds at the specified indices of escrowIdsByAddress. This function is used when a user wants to claim multiple escrowVaults at once (probably most of the time) prevention for gas overflow should be handled in the frontend/
function claimRewards(bytes32[] calldata _escrowIdsByAddress) external nonReentrant { uint256 total; for (uint256 i = 0; i < _escrowIdsByAddress.length; i++) { bytes32 _escrowId = _escrowIdsByAddress[i]; Escrow memory escrow = escrows[_escrowId]; require(msg.sender == escrow.account, "unauthorized"); uint256 reward = _claimReward(_escrowId); total += reward; } require(total > 0, "no rewards"); POP.safeTransfer(msg.sender, total); emit RewardsClaimed(msg.sender, total); }
3,776,674
/** *Submitted for verification at Etherscan.io on 2021-06-15 */ // File: @openzeppelin/upgrades/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.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 is Initializable { // 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: @openzeppelin/contracts-ethereum-package/contracts/introspection/IERC165.sol pragma solidity ^0.5.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-ethereum-package/contracts/token/ERC721/IERC721.sol pragma solidity ^0.5.0; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is Initializable, IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { 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: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @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 Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ 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: @openzeppelin/contracts-ethereum-package/contracts/drafts/Counters.sol pragma solidity ^0.5.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. 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;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; 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 { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: @openzeppelin/contracts-ethereum-package/contracts/introspection/ERC165.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is Initializable, IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; function initialize() public initializer { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[50] private ______gap; } // File: contracts/ERC721.sol pragma solidity ^0.5.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Initializable, Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // 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 to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; function initialize() public initializer { ERC165.initialize(); // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } function _hasBeenInitialized() internal view returns (bool) { return supportsInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return 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), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, 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. * * This is an internal detail of the `ERC721` contract and its use is deprecated. * @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) internal returns (bool) { if (!to.isContract()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is Initializable, IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } // File: contracts/ERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Initializable, Context, ERC165, ERC721, IERC721Enumerable { // 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; // 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; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ function initialize() public initializer { require(ERC721._hasBeenInitialized()); // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } function _hasBeenInitialized() internal view returns (bool) { return supportsInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } // /** // * @dev Internal function to burn a specific token. // * Reverts if the token does not exist. // * Deprecated, use {ERC721-_burn} instead. // * @param owner owner of the token to burn // * @param tokenId uint256 ID of the token being burned // */ // function _burn(address owner, uint256 tokenId) internal { // super._burn(owner, tokenId); // _removeTokenFromOwnerEnumeration(owner, tokenId); // // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund // _ownedTokensIndex[tokenId] = 0; // // _removeTokenFromAllTokensEnumeration(tokenId); // } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @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 { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @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 = _ownedTokens[from].length.sub(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 _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @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.sub(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 // _allTokens.length--; // _allTokensIndex[tokenId] = 0; // } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Metadata.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is Initializable, IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts/ERC721Metadata.sol pragma solidity ^0.5.0; contract ERC721Metadata is Initializable, Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ function initialize(string memory name, string memory symbol) public initializer { require(ERC721._hasBeenInitialized()); _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } function _hasBeenInitialized() internal view returns (bool) { return supportsInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } // * // * @dev Internal function to burn a specific token. // * Reverts if the token does not exist. // * Deprecated, use _burn(uint256) instead. // * @param owner owner of the token to burn // * @param tokenId uint256 ID of the token being burned by the msg.sender // function _burn(address owner, uint256 tokenId) internal { // super._burn(owner, tokenId); // // Clear metadata (if any) // if (bytes(_tokenURIs[tokenId]).length != 0) { // delete _tokenURIs[tokenId]; // } // } uint256[50] private ______gap; } // File: contracts/AsyncArtwork_v2.sol pragma solidity ^0.5.12; // interface for the v1 contract interface AsyncArtwork_v1 { function getControlToken(uint256 controlTokenId) external view returns (int256[] memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // Copyright (C) 2020 Asynchronous Art, Inc. // GNU General Public License v3.0 // Full notice https://github.com/asyncart/async-contracts/blob/master/LICENSE contract AsyncArtwork_v2 is Initializable, ERC721, ERC721Enumerable, ERC721Metadata { // An event whenever the platform address is updated event PlatformAddressUpdated(address platformAddress); event PermissionUpdated( uint256 tokenId, address tokenOwner, address permissioned ); // An event whenever a creator is whitelisted with the token id and the layer count event CreatorWhitelisted( uint256 tokenId, uint256 layerCount, address creator ); // An event whenever royalty amount for a token is updated event PlatformSalePercentageUpdated( uint256 tokenId, uint256 platformFirstPercentage, uint256 platformSecondPercentage ); event DefaultPlatformSalePercentageUpdated( uint256 defaultPlatformFirstSalePercentage, uint256 defaultPlatformSecondSalePercentage ); // An event whenever artist secondary sale percentage is updated event ArtistSecondSalePercentUpdated(uint256 artistSecondPercentage); // An event whenever a bid is proposed event BidProposed(uint256 tokenId, uint256 bidAmount, address bidder); // An event whenever an bid is withdrawn event BidWithdrawn(uint256 tokenId); // An event whenever a buy now price has been set event BuyPriceSet(uint256 tokenId, uint256 price); // An event when a token has been sold event TokenSale( // the id of the token uint256 tokenId, // the price that the token was sold for uint256 salePrice, // the address of the buyer address buyer ); // An event when a token(s) first sale requirement has been waived event FirstSaleWaived( // the ids of the token uint256[] tokenIds ); // An event whenever a control token has been updated event ControlLeverUpdated( // the id of the token uint256 tokenId, // an optional amount that the updater sent to boost priority of the rendering uint256 priorityTip, // the number of times this control lever can now be updated int256 numRemainingUpdates, // the ids of the levers that were updated uint256[] leverIds, // the previous values that the levers had before this update (for clients who want to animate the change) int256[] previousValues, // the new updated value int256[] updatedValues ); // struct for a token that controls part of the artwork struct ControlToken { // number that tracks how many levers there are uint256 numControlLevers; // The number of update calls this token has (-1 for infinite) int256 numRemainingUpdates; // false by default, true once instantiated bool exists; // false by default, true once setup by the artist bool isSetup; // the levers that this control token can use mapping(uint256 => ControlLever) levers; } // struct for a lever on a control token that can be changed struct ControlLever { // // The minimum value this token can have (inclusive) int256 minValue; // The maximum value this token can have (inclusive) int256 maxValue; // The current value for this token int256 currentValue; // false by default, true once instantiated bool exists; } // struct for a pending bid struct PendingBid { // the address of the bidder address payable bidder; // the amount that they bid uint256 amount; // false by default, true once instantiated bool exists; } struct WhitelistReservation { // the address of the creator address creator; // the amount of layers they're expected to mint uint256 layerCount; } // track whether this token was sold the first time or not (used for determining whether to use first or secondary sale percentage) mapping(uint256 => bool) public tokenDidHaveFirstSale; // if a token's URI has been locked or not mapping(uint256 => bool) public tokenURILocked; // map control token ID to its buy price mapping(uint256 => uint256) public buyPrices; // mapping of addresses to credits for failed transfers mapping(address => uint256) public failedTransferCredits; // mapping of tokenId to percentage of sale that the platform gets on first sales mapping(uint256 => uint256) public platformFirstSalePercentages; // mapping of tokenId to percentage of sale that the platform gets on secondary sales mapping(uint256 => uint256) public platformSecondSalePercentages; // what tokenId creators are allowed to mint (and how many layers) mapping(uint256 => WhitelistReservation) public creatorWhitelist; // for each token, holds an array of the creator collaborators. For layer tokens it will likely just be [artist], for master tokens it may hold multiples mapping(uint256 => address payable[]) public uniqueTokenCreators; // map a control token ID to its highest bid mapping(uint256 => PendingBid) public pendingBids; // map a control token id to a control token struct mapping(uint256 => ControlToken) public controlTokenMapping; // mapping of addresses that are allowed to control tokens on your behalf mapping(address => mapping(uint256 => address)) public permissionedControllers; // the percentage of sale that an artist gets on secondary sales uint256 public artistSecondSalePercentage; // gets incremented to placehold for tokens not minted yet uint256 public expectedTokenSupply; // the minimum % increase for new bids coming uint256 public minBidIncreasePercent; // the address of the platform (for receving commissions and royalties) address payable public platformAddress; // the address of the contract that can upgrade from v1 to v2 tokens address public upgraderAddress; // the address of the contract that can whitelist artists to mint address public minterAddress; // v3 vairables uint256 public defaultPlatformFirstSalePercentage; uint256 public defaultPlatformSecondSalePercentage; function setup( string memory name, string memory symbol, uint256 initialExpectedTokenSupply, address _upgraderAddress ) public initializer { ERC721.initialize(); ERC721Enumerable.initialize(); ERC721Metadata.initialize(name, symbol); // starting royalty amounts artistSecondSalePercentage = 10; // intitialize the minimum bid increase percent minBidIncreasePercent = 1; // by default, the platformAddress is the address that mints this contract platformAddress = msg.sender; // set the upgrader address upgraderAddress = _upgraderAddress; // set the initial expected token supply expectedTokenSupply = initialExpectedTokenSupply; require(expectedTokenSupply > 0); } // modifier for only allowing the platform to make a call modifier onlyPlatform() { require(msg.sender == platformAddress); _; } // modifier for only allowing the minter to make a call modifier onlyMinter() { require(msg.sender == minterAddress); _; } modifier onlyWhitelistedCreator(uint256 masterTokenId, uint256 layerCount) { require(creatorWhitelist[masterTokenId].creator == msg.sender); require(creatorWhitelist[masterTokenId].layerCount == layerCount); _; } function setExpectedTokenSupply(uint256 newExpectedTokenSupply) external onlyPlatform { expectedTokenSupply = newExpectedTokenSupply; } // reserve a tokenID and layer count for a creator. Define a platform royalty percentage per art piece (some pieces have higher or lower amount) function whitelistTokenForCreator( address creator, uint256 masterTokenId, uint256 layerCount, uint256 platformFirstSalePercentage, uint256 platformSecondSalePercentage ) external onlyMinter { // the tokenID we're reserving must be the current expected token supply require(masterTokenId == expectedTokenSupply); // reserve the tokenID for this creator creatorWhitelist[masterTokenId] = WhitelistReservation( creator, layerCount ); // increase the expected token supply expectedTokenSupply = masterTokenId.add(layerCount).add(1); // define the platform percentages for this token here platformFirstSalePercentages[ masterTokenId ] = platformFirstSalePercentage; platformSecondSalePercentages[ masterTokenId ] = platformSecondSalePercentage; emit CreatorWhitelisted(masterTokenId, layerCount, creator); } // Allows the platform to change the minter address function updateMinterAddress(address newMinterAddress) external onlyPlatform { minterAddress = newMinterAddress; } // Allows the current platform address to update to something different function updatePlatformAddress(address payable newPlatformAddress) external onlyPlatform { platformAddress = newPlatformAddress; emit PlatformAddressUpdated(newPlatformAddress); } // Allows platform to waive the first sale requirement for a token (for charity events, special cases, etc) function waiveFirstSaleRequirement(uint256[] calldata tokenIds) external onlyPlatform { // This allows the token sale proceeds to go to the current owner (rather than be distributed amongst the token's creators) for (uint256 k = 0; k < tokenIds.length; k++) { tokenDidHaveFirstSale[tokenIds[k]] = true; } emit FirstSaleWaived(tokenIds); } // Allows platform to change the royalty percentage for a specific token function updatePlatformSalePercentage( uint256 tokenId, uint256 platformFirstSalePercentage, uint256 platformSecondSalePercentage ) external onlyPlatform { // set the percentages for this token platformFirstSalePercentages[tokenId] = platformFirstSalePercentage; platformSecondSalePercentages[tokenId] = platformSecondSalePercentage; // emit an event to notify that the platform percent for this token has changed emit PlatformSalePercentageUpdated( tokenId, platformFirstSalePercentage, platformSecondSalePercentage ); } // Allows platform to change the default sales percentages function updateDefaultPlatformSalePercentage( uint256 _defaultPlatformFirstSalePercentage, uint256 _defaultPlatformSecondSalePercentage ) external onlyPlatform { defaultPlatformFirstSalePercentage = _defaultPlatformFirstSalePercentage; defaultPlatformSecondSalePercentage = _defaultPlatformSecondSalePercentage; // emit an event to notify that the platform percent has changed emit DefaultPlatformSalePercentageUpdated( defaultPlatformFirstSalePercentage, defaultPlatformSecondSalePercentage ); } // Allows the platform to change the minimum percent increase for incoming bids function updateMinimumBidIncreasePercent(uint256 _minBidIncreasePercent) external onlyPlatform { require( (_minBidIncreasePercent > 0) && (_minBidIncreasePercent <= 50), "Bid increases must be within 0-50%" ); // set the new bid increase percent minBidIncreasePercent = _minBidIncreasePercent; } // Allow the platform to update a token's URI if it's not locked yet (for fixing tokens post mint process) function updateTokenURI(uint256 tokenId, string calldata tokenURI) external onlyPlatform { // ensure that this token exists require(_exists(tokenId)); // ensure that the URI for this token is not locked yet require(tokenURILocked[tokenId] == false); // update the token URI super._setTokenURI(tokenId, tokenURI); } // Locks a token's URI from being updated function lockTokenURI(uint256 tokenId) external onlyPlatform { // ensure that this token exists require(_exists(tokenId)); // lock this token's URI from being changed tokenURILocked[tokenId] = true; } // Allows platform to change the percentage that artists receive on secondary sales function updateArtistSecondSalePercentage( uint256 _artistSecondSalePercentage ) external onlyPlatform { // update the percentage that artists get on secondary sales artistSecondSalePercentage = _artistSecondSalePercentage; // emit an event to notify that the artist second sale percent has updated emit ArtistSecondSalePercentUpdated(artistSecondSalePercentage); } function setupControlToken( uint256 controlTokenId, string calldata controlTokenURI, int256[] calldata leverMinValues, int256[] calldata leverMaxValues, int256[] calldata leverStartValues, int256 numAllowedUpdates, address payable[] calldata additionalCollaborators ) external { // Hard cap the number of levers a single control token can have require(leverMinValues.length <= 500, "Too many control levers."); // Hard cap the number of collaborators a single control token can have require( additionalCollaborators.length <= 50, "Too many collaborators." ); // ensure that this token is not setup yet require( controlTokenMapping[controlTokenId].isSetup == false, "Already setup" ); // ensure that only the control token artist is attempting this mint require( uniqueTokenCreators[controlTokenId][0] == msg.sender, "Must be control token artist" ); // enforce that the length of all the array lengths are equal require( (leverMinValues.length == leverMaxValues.length) && (leverMaxValues.length == leverStartValues.length), "Values array mismatch" ); // require the number of allowed updates to be infinite (-1) or some finite number require( (numAllowedUpdates == -1) || (numAllowedUpdates > 0), "Invalid allowed updates" ); // mint the control token here super._safeMint(msg.sender, controlTokenId); // set token URI super._setTokenURI(controlTokenId, controlTokenURI); // create the control token controlTokenMapping[controlTokenId] = ControlToken( leverStartValues.length, numAllowedUpdates, true, true ); // create the control token levers now for (uint256 k = 0; k < leverStartValues.length; k++) { // enforce that maxValue is greater than or equal to minValue require( leverMaxValues[k] >= leverMinValues[k], "Max val must >= min" ); // enforce that currentValue is valid require( (leverStartValues[k] >= leverMinValues[k]) && (leverStartValues[k] <= leverMaxValues[k]), "Invalid start val" ); // add the lever to this token controlTokenMapping[controlTokenId].levers[k] = ControlLever( leverMinValues[k], leverMaxValues[k], leverStartValues[k], true ); } // the control token artist can optionally specify additional collaborators on this layer for (uint256 i = 0; i < additionalCollaborators.length; i++) { // can't provide burn address as collaborator require(additionalCollaborators[i] != address(0)); uniqueTokenCreators[controlTokenId].push( additionalCollaborators[i] ); } } // upgrade a token from the v1 contract to this v2 version function upgradeV1Token( uint256 tokenId, address v1Address, bool isControlToken, address to, uint256 platformFirstPercentageForToken, uint256 platformSecondPercentageForToken, bool hasTokenHadFirstSale, address payable[] calldata uniqueTokenCreatorsForToken ) external { // get reference to v1 token contract AsyncArtwork_v1 v1Token = AsyncArtwork_v1(v1Address); // require that only the upgrader address is calling this method require(msg.sender == upgraderAddress, "Only upgrader can call."); // preserve the unique token creators uniqueTokenCreators[tokenId] = uniqueTokenCreatorsForToken; if (isControlToken) { // preserve the control token details if it's a control token int256[] memory controlToken = v1Token.getControlToken(tokenId); // Require control token to be a valid size (multiple of 3) require(controlToken.length % 3 == 0, "Invalid control token."); // Require control token to have at least 1 lever require(controlToken.length > 0, "Control token must have levers"); // Setup the control token // Use -1 for numRemainingUpdates since v1 tokens were infinite use controlTokenMapping[tokenId] = ControlToken( controlToken.length / 3, -1, true, true ); // set each lever for the control token. getControlToken returns levers like: // [minValue, maxValue, curValue, minValue, maxValue, curValue, ...] so they always come in groups of 3 for (uint256 k = 0; k < controlToken.length; k += 3) { controlTokenMapping[tokenId].levers[k / 3] = ControlLever( controlToken[k], controlToken[k + 1], controlToken[k + 2], true ); } } // Set the royalty percentage for this token platformFirstSalePercentages[tokenId] = platformFirstPercentageForToken; platformSecondSalePercentages[ tokenId ] = platformSecondPercentageForToken; // whether this token has already had its first sale tokenDidHaveFirstSale[tokenId] = hasTokenHadFirstSale; // Mint and transfer the token to the original v1 token owner super._safeMint(to, tokenId); // set the same token URI super._setTokenURI(tokenId, v1Token.tokenURI(tokenId)); } function mintArtwork( uint256 masterTokenId, string calldata artworkTokenURI, address payable[] calldata controlTokenArtists, address payable[] calldata uniqueArtists ) external onlyWhitelistedCreator(masterTokenId, controlTokenArtists.length) { // Can't mint a token with ID 0 anymore require(masterTokenId > 0); // Mint the token that represents ownership of the entire artwork super._safeMint(msg.sender, masterTokenId); // set the token URI for this art super._setTokenURI(masterTokenId, artworkTokenURI); // set the unique artists array for future royalties uniqueTokenCreators[masterTokenId] = uniqueArtists; // iterate through all control token URIs (1 for each control token) for (uint256 i = 0; i < controlTokenArtists.length; i++) { // can't provide burn address as artist require(controlTokenArtists[i] != address(0)); // determine the tokenID for this control token uint256 controlTokenId = masterTokenId + i + 1; // add this control token artist to the unique creator list for that control token uniqueTokenCreators[controlTokenId].push(controlTokenArtists[i]); } } // Bidder functions function bid(uint256 tokenId) external payable { // don't allow bids of 0 require(msg.value > 0); // don't let owners/approved bid on their own tokens require(_isApprovedOrOwner(msg.sender, tokenId) == false); // check if there's a high bid if (pendingBids[tokenId].exists) { // enforce that this bid is higher by at least the minimum required percent increase require( msg.value >= ( pendingBids[tokenId] .amount .mul(minBidIncreasePercent.add(100)) .div(100) ), "Bid must increase by min %" ); // Return bid amount back to bidder safeFundsTransfer( pendingBids[tokenId].bidder, pendingBids[tokenId].amount ); } // set the new highest bid pendingBids[tokenId] = PendingBid(msg.sender, msg.value, true); // Emit event for the bid proposal emit BidProposed(tokenId, msg.value, msg.sender); } // allows an address with a pending bid to withdraw it function withdrawBid(uint256 tokenId) external { // check that there is a bid from the sender to withdraw (also allows platform address to withdraw a bid on someone's behalf) require( (pendingBids[tokenId].bidder == msg.sender) || (msg.sender == platformAddress) ); // attempt to withdraw the bid _withdrawBid(tokenId); } function _withdrawBid(uint256 tokenId) internal { require(pendingBids[tokenId].exists); // Return bid amount back to bidder safeFundsTransfer( pendingBids[tokenId].bidder, pendingBids[tokenId].amount ); // clear highest bid pendingBids[tokenId] = PendingBid(address(0), 0, false); // emit an event when the highest bid is withdrawn emit BidWithdrawn(tokenId); } // Buy the artwork for the currently set price // Allows the buyer to specify an expected remaining uses they'll accept function takeBuyPrice(uint256 tokenId, int256 expectedRemainingUpdates) external payable { // don't let owners/approved buy their own tokens require(_isApprovedOrOwner(msg.sender, tokenId) == false); // get the sale amount uint256 saleAmount = buyPrices[tokenId]; // check that there is a buy price require(saleAmount > 0); // check that the buyer sent exact amount to purchase require(msg.value == saleAmount); // if this is a control token if (controlTokenMapping[tokenId].exists) { // ensure that the remaining uses on the token is equal to what buyer expects require( controlTokenMapping[tokenId].numRemainingUpdates == expectedRemainingUpdates ); } // Return all highest bidder's money if (pendingBids[tokenId].exists) { // Return bid amount back to bidder safeFundsTransfer( pendingBids[tokenId].bidder, pendingBids[tokenId].amount ); // clear highest bid pendingBids[tokenId] = PendingBid(address(0), 0, false); } onTokenSold(tokenId, saleAmount, msg.sender); } // Take an amount and distribute it evenly amongst a list of creator addresses function distributeFundsToCreators( uint256 amount, address payable[] memory creators ) private { if (creators.length > 0) { uint256 creatorShare = amount.div(creators.length); for (uint256 i = 0; i < creators.length; i++) { safeFundsTransfer(creators[i], creatorShare); } } } // When a token is sold via list price or bid. Distributes the sale amount to the unique token creators and transfer // the token to the new owner function onTokenSold( uint256 tokenId, uint256 saleAmount, address to ) private { // if the first sale already happened, then give the artist + platform the secondary royalty percentage if (tokenDidHaveFirstSale[tokenId]) { // give platform its secondary sale percentage uint256 platformAmount; if (platformSecondSalePercentages[tokenId] == 0) { // default amount platformAmount = saleAmount .mul(defaultPlatformSecondSalePercentage) .div(100); } else { platformAmount = saleAmount .mul(platformSecondSalePercentages[tokenId]) .div(100); } safeFundsTransfer(platformAddress, platformAmount); // distribute the creator royalty amongst the creators (all artists involved for a base token, sole artist creator for layer ) uint256 creatorAmount = saleAmount.mul(artistSecondSalePercentage).div(100); distributeFundsToCreators( creatorAmount, uniqueTokenCreators[tokenId] ); // cast the owner to a payable address address payable payableOwner = address(uint160(ownerOf(tokenId))); // transfer the remaining amount to the owner of the token safeFundsTransfer( payableOwner, saleAmount.sub(platformAmount).sub(creatorAmount) ); } else { tokenDidHaveFirstSale[tokenId] = true; // give platform its first sale percentage uint256 platformAmount; if (platformFirstSalePercentages[tokenId] == 0) { // default value platformAmount = saleAmount .mul(defaultPlatformFirstSalePercentage) .div(100); } else { platformAmount = saleAmount .mul(platformFirstSalePercentages[tokenId]) .div(100); } safeFundsTransfer(platformAddress, platformAmount); // this is a token first sale, so distribute the remaining funds to the unique token creators of this token // (if it's a base token it will be all the unique creators, if it's a control token it will be that single artist) distributeFundsToCreators( saleAmount.sub(platformAmount), uniqueTokenCreators[tokenId] ); } // clear highest bid pendingBids[tokenId] = PendingBid(address(0), 0, false); // Transfer token to msg.sender _transferFrom(ownerOf(tokenId), to, tokenId); // Emit event emit TokenSale(tokenId, saleAmount, to); } // Owner functions // Allow owner to accept the highest bid for a token function acceptBid(uint256 tokenId, uint256 minAcceptedAmount) external { // check if sender is owner/approved of token require(_isApprovedOrOwner(msg.sender, tokenId)); // check if there's a bid to accept require(pendingBids[tokenId].exists); // check that the current pending bid amount is at least what the accepting owner expects require(pendingBids[tokenId].amount >= minAcceptedAmount); // process the sale onTokenSold( tokenId, pendingBids[tokenId].amount, pendingBids[tokenId].bidder ); } // Allows owner of a control token to set an immediate buy price. Set to 0 to reset. function makeBuyPrice(uint256 tokenId, uint256 amount) external { // check if sender is owner/approved of token require(_isApprovedOrOwner(msg.sender, tokenId)); // set the buy price buyPrices[tokenId] = amount; // emit event emit BuyPriceSet(tokenId, amount); } // return the number of times that a control token can be used function getNumRemainingControlUpdates(uint256 controlTokenId) external view returns (int256) { require( controlTokenMapping[controlTokenId].isSetup, "Token does not exist." ); return controlTokenMapping[controlTokenId].numRemainingUpdates; } // return the min, max, and current value of a control lever function getControlToken(uint256 controlTokenId) external view returns (int256[] memory) { require( controlTokenMapping[controlTokenId].isSetup, "Token does not exist." ); ControlToken storage controlToken = controlTokenMapping[controlTokenId]; int256[] memory returnValues = new int256[](controlToken.numControlLevers.mul(3)); uint256 returnValIndex = 0; // iterate through all the control levers for this control token for (uint256 i = 0; i < controlToken.numControlLevers; i++) { returnValues[returnValIndex] = controlToken.levers[i].minValue; returnValIndex = returnValIndex.add(1); returnValues[returnValIndex] = controlToken.levers[i].maxValue; returnValIndex = returnValIndex.add(1); returnValues[returnValIndex] = controlToken.levers[i].currentValue; returnValIndex = returnValIndex.add(1); } return returnValues; } // anyone can grant permission to another address to control a specific token on their behalf. Set to Address(0) to reset. function grantControlPermission(uint256 tokenId, address permissioned) external { permissionedControllers[msg.sender][tokenId] = permissioned; emit PermissionUpdated(tokenId, msg.sender, permissioned); } // Allows owner (or permissioned user) of a control token to update its lever values // Optionally accept a payment to increase speed of rendering priority function useControlToken( uint256 controlTokenId, uint256[] calldata leverIds, int256[] calldata newValues ) external payable { // check if sender is owner/approved of token OR if they're a permissioned controller for the token owner require( _isApprovedOrOwner(msg.sender, controlTokenId) || (permissionedControllers[ownerOf(controlTokenId)][ controlTokenId ] == msg.sender), "Owner or permissioned only" ); // check if control exists require( controlTokenMapping[controlTokenId].isSetup, "Token does not exist." ); // get the control token reference ControlToken storage controlToken = controlTokenMapping[controlTokenId]; // check that number of uses for control token is either infinite or is positive require( (controlToken.numRemainingUpdates == -1) || (controlToken.numRemainingUpdates > 0), "No more updates allowed" ); // collect the previous lever values for the event emit below int256[] memory previousValues = new int256[](newValues.length); for (uint256 i = 0; i < leverIds.length; i++) { // get the control lever ControlLever storage lever = controlTokenMapping[controlTokenId].levers[leverIds[i]]; // Enforce that the new value is valid require( (newValues[i] >= lever.minValue) && (newValues[i] <= lever.maxValue), "Invalid val" ); // Enforce that the new value is different require( newValues[i] != lever.currentValue, "Must provide different val" ); // grab previous value for the event emit previousValues[i] = lever.currentValue; // Update token current value lever.currentValue = newValues[i]; } // if there's a payment then send it to the platform (for higher priority updates) if (msg.value > 0) { safeFundsTransfer(platformAddress, msg.value); } // if this control token is finite in its uses if (controlToken.numRemainingUpdates > 0) { // decrease it down by 1 controlToken.numRemainingUpdates = controlToken.numRemainingUpdates - 1; // since we used one of those updates, withdraw any existing bid for this token if exists if (pendingBids[controlTokenId].exists) { _withdrawBid(controlTokenId); } } // emit event emit ControlLeverUpdated( controlTokenId, msg.value, controlToken.numRemainingUpdates, leverIds, previousValues, newValues ); } // Allows a user to withdraw all failed transaction credits function withdrawAllFailedCredits() external { uint256 amount = failedTransferCredits[msg.sender]; require(amount != 0); require(address(this).balance >= amount); failedTransferCredits[msg.sender] = 0; (bool successfulWithdraw, ) = msg.sender.call.value(amount)(""); require(successfulWithdraw); } // Safely transfer funds and if fail then store that amount as credits for a later pull function safeFundsTransfer(address payable recipient, uint256 amount) internal { // attempt to send the funds to the recipient (bool success, ) = recipient.call.value(amount).gas(2300)(""); // if it failed, update their credit balance so they can pull it later if (success == false) { failedTransferCredits[recipient] = failedTransferCredits[recipient] .add(amount); } } // override the default transfer function _transferFrom( address from, address to, uint256 tokenId ) internal { // clear a buy now price buyPrices[tokenId] = 0; // transfer the token super._transferFrom(from, to, tokenId); } }
override the default transfer clear a buy now price transfer the token
function _transferFrom( address from, address to, uint256 tokenId ) internal { buyPrices[tokenId] = 0; super._transferFrom(from, to, tokenId); }
2,041,817
/** *Submitted for verification at Etherscan.io on 2021-03-31 */ /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.12; contract GemLike { function allowance(address, address) public returns (uint); function approve(address, uint) public; function transfer(address, uint) public returns (bool); function transferFrom(address, address, uint) public returns (bool); } contract ValueLike { function peek() public returns (uint, bool); } contract SaiTubLike { function skr() public view returns (GemLike); function gem() public view returns (GemLike); function gov() public view returns (GemLike); function sai() public view returns (GemLike); function pep() public view returns (ValueLike); function vox() public view returns (VoxLike); function bid(uint) public view returns (uint); function ink(bytes32) public view returns (uint); function tag() public view returns (uint); function tab(bytes32) public returns (uint); function rap(bytes32) public returns (uint); function draw(bytes32, uint) public; function shut(bytes32) public; function exit(uint) public; function give(bytes32, address) public; } contract VoxLike { function par() public returns (uint); } contract JoinLike { function ilk() public returns (bytes32); function gem() public returns (GemLike); function dai() public returns (GemLike); function join(address, uint) public; function exit(address, uint) public; } contract VatLike { function ilks(bytes32) public view returns (uint, uint, uint, uint, uint); function hope(address) public; function frob(bytes32, address, address, address, int, int) public; } contract ManagerLike { function vat() public view returns (address); function urns(uint) public view returns (address); function open(bytes32, address) public returns (uint); function frob(uint, int, int) public; function give(uint, address) public; function move(uint, address, uint) public; } contract OtcLike { function getPayAmount(address, address, uint) public view returns (uint); function buyAllAmount(address, uint, address, uint) public; } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as `account`'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } /** * @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); } /** * @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; } } /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** * @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. */ contract ReentrancyGuard is Initializable { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; function initialize() public initializer { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } uint256[50] private ______gap; } /** * @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]; } } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ contract ICErc20 { address public underlying; function mint(uint256 mintAmount) external returns (uint); function redeemUnderlying(uint256 redeemAmount) external returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getCash() external view returns (uint); function supplyRatePerBlock() external view returns (uint); } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @author Brendan Asselstine * @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias. * @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94 */ library UniformRandomNumber { /// @notice Select a random number without modulo bias using a random seed and upper bound /// @param _entropy The seed for randomness /// @param _upperBound The upper bound of the desired number /// @return A random number less than the _upperBound function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) { require(_upperBound > 0, "UniformRand/min-bound"); uint256 min = -_upperBound % _upperBound; uint256 random = _entropy; while (true) { if (random >= min) { break; } random = uint256(keccak256(abi.encodePacked(random))); } return random % _upperBound; } } /** * @reviewers: [@clesaege, @unknownunknown1, @ferittuncer] * @auditors: [] * @bounties: [<14 days 10 ETH max payout>] * @deployments: [] */ /** * @title SortitionSumTreeFactory * @author Enrique Piqueras - <[email protected]> * @dev A factory of trees that keep track of staked values for sortition. */ library SortitionSumTreeFactory { /* Structs */ struct SortitionSumTree { uint K; // The maximum number of childs per node. // We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around. uint[] stack; uint[] nodes; // Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node. mapping(bytes32 => uint) IDsToNodeIndexes; mapping(uint => bytes32) nodeIndexesToIDs; } /* Storage */ struct SortitionSumTrees { mapping(bytes32 => SortitionSumTree) sortitionSumTrees; } /* internal */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K The number of children each node in the tree should have. */ function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; require(tree.K == 0, "Tree already exists."); require(_K > 1, "K must be greater than one."); tree.K = _K; tree.stack.length = 0; tree.nodes.length = 0; tree.nodes.push(0); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) { // No existing node. if (_value != 0) { // Non zero value. // Append. // Add node. if (tree.stack.length == 0) { // No vacant spots. // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.length--; tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; updateParents(self, _key, treeIndex, true, _value); } } else { // Existing node. if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. uint value = tree.nodes[treeIndex]; tree.nodes[treeIndex] = 0; // Push to stack. tree.stack.push(treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[treeIndex]; updateParents(self, _key, treeIndex, false, value); } else if (_value != tree.nodes[treeIndex]) { // New, non zero value. // Set. bool plusOrMinus = tree.nodes[treeIndex] <= _value; uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value; tree.nodes[treeIndex] = _value; updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue); } } } /* internal Views */ /** * @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination. * `O(n)` where * `n` is the maximum number of nodes ever appended. */ function queryLeafs( SortitionSumTrees storage self, bytes32 _key, uint _cursor, uint _count ) internal view returns(uint startIndex, uint[] memory values, bool hasMore) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; // Find the start index. for (uint i = 0; i < tree.nodes.length; i++) { if ((tree.K * i) + 1 >= tree.nodes.length) { startIndex = i; break; } } // Get the values. uint loopStartIndex = startIndex + _cursor; values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count); uint valuesIndex = 0; for (uint j = loopStartIndex; j < tree.nodes.length; j++) { if (valuesIndex < _count) { values[valuesIndex] = tree.nodes[j]; valuesIndex++; } else { hasMore = true; break; } } } /** * @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return The drawn ID. * `O(k * log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = 0; uint currentDrawnNumber = _drawnNumber % tree.nodes[0]; while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children. for (uint i = 1; i <= tree.K; i++) { // Loop over children. uint nodeIndex = (tree.K * treeIndex) + i; uint nodeValue = tree.nodes[nodeIndex]; if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. else { // Pick this child. treeIndex = nodeIndex; break; } } ID = tree.nodeIndexesToIDs[treeIndex]; } /** @dev Gets a specified ID's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return The associated value. */ function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) value = 0; else value = tree.nodes[treeIndex]; } function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; if (tree.nodes.length == 0) { return 0; } else { return tree.nodes[0]; } } /* Private */ /** * @dev Update all the parents of a node. * @param _key The key of the tree to update. * @param _treeIndex The index of the node to start from. * @param _plusOrMinus Wether to add (true) or substract (false). * @param _value The value to add or substract. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } } } /** * @author Brendan Asselstine * @notice Tracks committed and open balances for addresses. Affords selection of an address by indexing all committed balances. * * Balances are tracked in Draws. There is always one open Draw. Deposits are always added to the open Draw. * When a new draw is opened, the previous opened draw is committed. * * The committed balance for an address is the total of their balances for committed Draws. * An address's open balance is their balance in the open Draw. */ library DrawManager { using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; using SafeMath for uint256; /** * The ID to use for the selection tree. */ bytes32 public constant TREE_OF_DRAWS = "TreeOfDraws"; uint8 public constant MAX_BRANCHES_PER_NODE = 10; /** * Stores information for all draws. */ struct State { /** * Each Draw stores it's address balances in a sortitionSumTree. Draw trees are indexed using the Draw index. * There is one root sortitionSumTree that stores all of the draw totals. The root tree is indexed using the constant TREE_OF_DRAWS. */ SortitionSumTreeFactory.SortitionSumTrees sortitionSumTrees; /** * Stores the consolidated draw index that an address deposited to. */ mapping(address => uint256) consolidatedDrawIndices; /** * Stores the last Draw index that an address deposited to. */ mapping(address => uint256) latestDrawIndices; /** * Stores a mapping of Draw index => Draw total */ mapping(uint256 => uint256) __deprecated__drawTotals; /** * The current open Draw index */ uint256 openDrawIndex; /** * The total of committed balances */ uint256 __deprecated__committedSupply; } /** * @notice Opens the next Draw and commits the previous open Draw (if any). * @param self The drawState this library is attached to * @return The index of the new open Draw */ function openNextDraw(State storage self) public returns (uint256) { if (self.openDrawIndex == 0) { // If there is no previous draw, we must initialize self.sortitionSumTrees.createTree(TREE_OF_DRAWS, MAX_BRANCHES_PER_NODE); } else { // else add current draw to sortition sum trees bytes32 drawId = bytes32(self.openDrawIndex); uint256 drawTotal = openSupply(self); self.sortitionSumTrees.set(TREE_OF_DRAWS, drawTotal, drawId); } // now create a new draw uint256 drawIndex = self.openDrawIndex.add(1); self.sortitionSumTrees.createTree(bytes32(drawIndex), MAX_BRANCHES_PER_NODE); self.openDrawIndex = drawIndex; return drawIndex; } /** * @notice Deposits the given amount into the current open draw by the given user. * @param self The DrawManager state * @param _addr The address to deposit for * @param _amount The amount to deposit */ function deposit(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openDrawIndex = self.openDrawIndex; // update the current draw uint256 currentAmount = self.sortitionSumTrees.stakeOf(bytes32(openDrawIndex), userId); currentAmount = currentAmount.add(_amount); drawSet(self, openDrawIndex, currentAmount, _addr); uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; // if this is the user's first draw, set it if (consolidatedDrawIndex == 0) { self.consolidatedDrawIndices[_addr] = openDrawIndex; // otherwise, if the consolidated draw is not this draw } else if (consolidatedDrawIndex != openDrawIndex) { // if a second draw does not exist if (latestDrawIndex == 0) { // set the second draw to the current draw self.latestDrawIndices[_addr] = openDrawIndex; // otherwise if a second draw exists but is not the current one } else if (latestDrawIndex != openDrawIndex) { // merge it into the first draw, and update the second draw index to this one uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId); uint256 latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId); drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(latestAmount), _addr); drawSet(self, latestDrawIndex, 0, _addr); self.latestDrawIndices[_addr] = openDrawIndex; } } } /** * @notice Deposits into a user's committed balance, thereby bypassing the open draw. * @param self The DrawManager state * @param _addr The address of the user for whom to deposit * @param _amount The amount to deposit */ function depositCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; // if they have a committed balance if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) { uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId); drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(_amount), _addr); } else { // they must not have any committed balance self.latestDrawIndices[_addr] = consolidatedDrawIndex; self.consolidatedDrawIndices[_addr] = self.openDrawIndex.sub(1); drawSet(self, self.consolidatedDrawIndices[_addr], _amount, _addr); } } /** * @notice Withdraws a user's committed and open draws. * @param self The DrawManager state * @param _addr The address whose balance to withdraw */ function withdraw(State storage self, address _addr) public requireOpenDraw(self) onlyNonZero(_addr) { uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; if (consolidatedDrawIndex != 0) { drawSet(self, consolidatedDrawIndex, 0, _addr); delete self.consolidatedDrawIndices[_addr]; } if (latestDrawIndex != 0) { drawSet(self, latestDrawIndex, 0, _addr); delete self.latestDrawIndices[_addr]; } } /** * @notice Withdraw's from a user's open balance * @param self The DrawManager state * @param _addr The user to withdrawn from * @param _amount The amount to withdraw */ function withdrawOpen(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openTotal = self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), userId); require(_amount <= openTotal, "DrawMan/exceeds-open"); uint256 remaining = openTotal.sub(_amount); drawSet(self, self.openDrawIndex, remaining, _addr); } /** * @notice Withdraw's from a user's committed balance. Fails if the user attempts to take more than available. * @param self The DrawManager state * @param _addr The user to withdraw from * @param _amount The amount to withdraw. */ function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; uint256 consolidatedAmount = 0; uint256 latestAmount = 0; uint256 total = 0; if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) { latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId); total = total.add(latestAmount); } if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) { consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId); total = total.add(consolidatedAmount); } // If the total is greater than zero, then consolidated *must* have the committed balance // However, if the total is zero then the consolidated balance may be the open balance if (total == 0) { return; } require(_amount <= total, "Pool/exceed"); uint256 remaining = total.sub(_amount); // if there was a second amount that needs to be updated if (remaining > consolidatedAmount) { uint256 secondRemaining = remaining.sub(consolidatedAmount); drawSet(self, latestDrawIndex, secondRemaining, _addr); } else if (latestAmount > 0) { // else delete the second amount if it exists delete self.latestDrawIndices[_addr]; drawSet(self, latestDrawIndex, 0, _addr); } // if the consolidated amount needs to be destroyed if (remaining == 0) { delete self.consolidatedDrawIndices[_addr]; drawSet(self, consolidatedDrawIndex, 0, _addr); } else if (remaining < consolidatedAmount) { drawSet(self, consolidatedDrawIndex, remaining, _addr); } } /** * @notice Returns the total balance for an address, including committed balances and the open balance. */ function balanceOf(State storage drawState, address _addr) public view returns (uint256) { return committedBalanceOf(drawState, _addr).add(openBalanceOf(drawState, _addr)); } /** * @notice Returns the total committed balance for an address. * @param self The DrawManager state * @param _addr The address whose committed balance should be returned * @return The total committed balance */ function committedBalanceOf(State storage self, address _addr) public view returns (uint256) { uint256 balance = 0; uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) { balance = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), bytes32(uint256(_addr))); } if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) { balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), bytes32(uint256(_addr)))); } return balance; } /** * @notice Returns the open balance for an address * @param self The DrawManager state * @param _addr The address whose open balance should be returned * @return The open balance */ function openBalanceOf(State storage self, address _addr) public view returns (uint256) { if (self.openDrawIndex == 0) { return 0; } else { return self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), bytes32(uint256(_addr))); } } /** * @notice Returns the open Draw balance for the DrawManager * @param self The DrawManager state * @return The open draw total balance */ function openSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(bytes32(self.openDrawIndex)); } /** * @notice Returns the committed balance for the DrawManager * @param self The DrawManager state * @return The total committed balance */ function committedSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(TREE_OF_DRAWS); } /** * @notice Updates the Draw balance for an address. * @param self The DrawManager state * @param _drawIndex The Draw index * @param _amount The new balance * @param _addr The address whose balance should be updated */ function drawSet(State storage self, uint256 _drawIndex, uint256 _amount, address _addr) internal { bytes32 drawId = bytes32(_drawIndex); bytes32 userId = bytes32(uint256(_addr)); uint256 oldAmount = self.sortitionSumTrees.stakeOf(drawId, userId); if (oldAmount != _amount) { // If the amount has changed // Update the Draw's balance for that address self.sortitionSumTrees.set(drawId, _amount, userId); // if the draw is committed if (_drawIndex != self.openDrawIndex) { // Get the new draw total uint256 newDrawTotal = self.sortitionSumTrees.total(drawId); // update the draw in the committed tree self.sortitionSumTrees.set(TREE_OF_DRAWS, newDrawTotal, drawId); } } } /** * @notice Selects an address by indexing into the committed tokens using the passed token. * If there is no committed supply, the zero address is returned. * @param self The DrawManager state * @param _token The token index to select * @return The selected address */ function draw(State storage self, uint256 _token) public view returns (address) { // If there is no one to select, just return the zero address if (committedSupply(self) == 0) { return address(0); } require(_token < committedSupply(self), "Pool/ineligible"); bytes32 drawIndex = self.sortitionSumTrees.draw(TREE_OF_DRAWS, _token); uint256 drawSupply = self.sortitionSumTrees.total(drawIndex); uint256 drawToken = _token % drawSupply; return address(uint256(self.sortitionSumTrees.draw(drawIndex, drawToken))); } /** * @notice Selects an address using the entropy as an index into the committed tokens * The entropy is passed into the UniformRandomNumber library to remove modulo bias. * @param self The DrawManager state * @param _entropy The random entropy to use * @return The selected address */ function drawWithEntropy(State storage self, bytes32 _entropy) public view returns (address) { uint256 bound = committedSupply(self); address selected; if (bound == 0) { selected = address(0); } else { selected = draw(self, UniformRandomNumber.uniform(uint256(_entropy), bound)); } return selected; } modifier requireOpenDraw(State storage self) { require(self.openDrawIndex > 0, "Pool/no-open"); _; } modifier requireCommittedDraw(State storage self) { require(self.openDrawIndex > 1, "Pool/no-commit"); _; } modifier onlyNonZero(address _addr) { require(_addr != address(0), "Pool/not-zero"); _; } } /** * @title FixidityLib * @author Gadi Guy, Alberto Cuesta Canada * @notice This library provides fixed point arithmetic with protection against * overflow. * All operations are done with int256 and the operands must have been created * with any of the newFrom* functions, which shift the comma digits() to the * right and check for limits. * When using this library be sure of using maxNewFixed() as the upper limit for * creation of fixed point numbers. Use maxFixedMul(), maxFixedDiv() and * maxFixedAdd() if you want to be certain that those operations don't * overflow. */ library FixidityLib { /** * @notice Number of positions that the comma is shifted to the right. */ function digits() public pure returns(uint8) { return 24; } /** * @notice This is 1 in the fixed point units used in this library. * @dev Test fixed1() equals 10^digits() * Hardcoded to 24 digits. */ function fixed1() public pure returns(int256) { return 1000000000000000000000000; } /** * @notice The amount of decimals lost on each multiplication operand. * @dev Test mulPrecision() equals sqrt(fixed1) * Hardcoded to 24 digits. */ function mulPrecision() public pure returns(int256) { return 1000000000000; } /** * @notice Maximum value that can be represented in an int256 * @dev Test maxInt256() equals 2^255 -1 */ function maxInt256() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282019728792003956564819967; } /** * @notice Minimum value that can be represented in an int256 * @dev Test minInt256 equals (2^255) * (-1) */ function minInt256() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282019728792003956564819968; } /** * @notice Maximum value that can be converted to fixed point. Optimize for * @dev deployment. * Test maxNewFixed() equals maxInt256() / fixed1() * Hardcoded to 24 digits. */ function maxNewFixed() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Minimum value that can be converted to fixed point. Optimize for * deployment. * @dev Test minNewFixed() equals -(maxInt256()) / fixed1() * Hardcoded to 24 digits. */ function minNewFixed() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as an addition operator. * @dev Test maxFixedAdd() equals maxInt256()-1 / 2 * Test add(maxFixedAdd(),maxFixedAdd()) equals maxFixedAdd() + maxFixedAdd() * Test add(maxFixedAdd()+1,maxFixedAdd()) throws * Test add(-maxFixedAdd(),-maxFixedAdd()) equals -maxFixedAdd() - maxFixedAdd() * Test add(-maxFixedAdd(),-maxFixedAdd()-1) throws */ function maxFixedAdd() public pure returns(int256) { return 28948022309329048855892746252171976963317496166410141009864396001978282409983; } /** * @notice Maximum negative value that can be safely in a subtraction. * @dev Test maxFixedSub() equals minInt256() / 2 */ function maxFixedSub() public pure returns(int256) { return -28948022309329048855892746252171976963317496166410141009864396001978282409984; } /** * @notice Maximum value that can be safely used as a multiplication operator. * @dev Calculated as sqrt(maxInt256()*fixed1()). * Be careful with your sqrt() implementation. I couldn't find a calculator * that would give the exact square root of maxInt256*fixed1 so this number * is below the real number by no more than 3*10**28. It is safe to use as * a limit for your multiplications, although powers of two of numbers over * this value might still work. * Test multiply(maxFixedMul(),maxFixedMul()) equals maxFixedMul() * maxFixedMul() * Test multiply(maxFixedMul(),maxFixedMul()+1) throws * Test multiply(-maxFixedMul(),maxFixedMul()) equals -maxFixedMul() * maxFixedMul() * Test multiply(-maxFixedMul(),maxFixedMul()+1) throws * Hardcoded to 24 digits. */ function maxFixedMul() public pure returns(int256) { return 240615969168004498257251713877715648331380787511296; } /** * @notice Maximum value that can be safely used as a dividend. * @dev divide(maxFixedDiv,newFixedFraction(1,fixed1())) = maxInt256(). * Test maxFixedDiv() equals maxInt256()/fixed1() * Test divide(maxFixedDiv(),multiply(mulPrecision(),mulPrecision())) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,multiply(mulPrecision(),mulPrecision())) throws * Hardcoded to 24 digits. */ function maxFixedDiv() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as a divisor. * @dev Test maxFixedDivisor() equals fixed1()*fixed1() - Or 10**(digits()*2) * Test divide(10**(digits()*2 + 1),10**(digits()*2)) = returns 10*fixed1() * Test divide(10**(digits()*2 + 1),10**(digits()*2 + 1)) = throws * Hardcoded to 24 digits. */ function maxFixedDivisor() public pure returns(int256) { return 1000000000000000000000000000000000000000000000000; } /** * @notice Converts an int256 to fixed point units, equivalent to multiplying * by 10^digits(). * @dev Test newFixed(0) returns 0 * Test newFixed(1) returns fixed1() * Test newFixed(maxNewFixed()) returns maxNewFixed() * fixed1() * Test newFixed(maxNewFixed()+1) fails */ function newFixed(int256 x) public pure returns (int256) { require(x <= maxNewFixed()); require(x >= minNewFixed()); return x * fixed1(); } /** * @notice Converts an int256 in the fixed point representation of this * library to a non decimal. All decimal digits will be truncated. */ function fromFixed(int256 x) public pure returns (int256) { return x / fixed1(); } /** * @notice Converts an int256 which is already in some fixed point * representation to a different fixed precision representation. * Both the origin and destination precisions must be 38 or less digits. * Origin values with a precision higher than the destination precision * will be truncated accordingly. * @dev * Test convertFixed(1,0,0) returns 1; * Test convertFixed(1,1,1) returns 1; * Test convertFixed(1,1,0) returns 0; * Test convertFixed(1,0,1) returns 10; * Test convertFixed(10,1,0) returns 1; * Test convertFixed(10,0,1) returns 100; * Test convertFixed(100,1,0) returns 10; * Test convertFixed(100,0,1) returns 1000; * Test convertFixed(1000,2,0) returns 10; * Test convertFixed(1000,0,2) returns 100000; * Test convertFixed(1000,2,1) returns 100; * Test convertFixed(1000,1,2) returns 10000; * Test convertFixed(maxInt256,1,0) returns maxInt256/10; * Test convertFixed(maxInt256,0,1) throws * Test convertFixed(maxInt256,38,0) returns maxInt256/(10**38); * Test convertFixed(1,0,38) returns 10**38; * Test convertFixed(maxInt256,39,0) throws * Test convertFixed(1,0,39) throws */ function convertFixed(int256 x, uint8 _originDigits, uint8 _destinationDigits) public pure returns (int256) { require(_originDigits <= 38 && _destinationDigits <= 38); uint8 decimalDifference; if ( _originDigits > _destinationDigits ){ decimalDifference = _originDigits - _destinationDigits; return x/(uint128(10)**uint128(decimalDifference)); } else if ( _originDigits < _destinationDigits ){ decimalDifference = _destinationDigits - _originDigits; // Cast uint8 -> uint128 is safe // Exponentiation is safe: // _originDigits and _destinationDigits limited to 38 or less // decimalDifference = abs(_destinationDigits - _originDigits) // decimalDifference < 38 // 10**38 < 2**128-1 require(x <= maxInt256()/uint128(10)**uint128(decimalDifference)); require(x >= minInt256()/uint128(10)**uint128(decimalDifference)); return x*(uint128(10)**uint128(decimalDifference)); } // _originDigits == digits()) return x; } /** * @notice Converts an int256 which is already in some fixed point * representation to that of this library. The _originDigits parameter is the * precision of x. Values with a precision higher than FixidityLib.digits() * will be truncated accordingly. */ function newFixed(int256 x, uint8 _originDigits) public pure returns (int256) { return convertFixed(x, _originDigits, digits()); } /** * @notice Converts an int256 in the fixed point representation of this * library to a different representation. The _destinationDigits parameter is the * precision of the output x. Values with a precision below than * FixidityLib.digits() will be truncated accordingly. */ function fromFixed(int256 x, uint8 _destinationDigits) public pure returns (int256) { return convertFixed(x, digits(), _destinationDigits); } /** * @notice Converts two int256 representing a fraction to fixed point units, * equivalent to multiplying dividend and divisor by 10^digits(). * @dev * Test newFixedFraction(maxFixedDiv()+1,1) fails * Test newFixedFraction(1,maxFixedDiv()+1) fails * Test newFixedFraction(1,0) fails * Test newFixedFraction(0,1) returns 0 * Test newFixedFraction(1,1) returns fixed1() * Test newFixedFraction(maxFixedDiv(),1) returns maxFixedDiv()*fixed1() * Test newFixedFraction(1,fixed1()) returns 1 * Test newFixedFraction(1,fixed1()-1) returns 0 */ function newFixedFraction( int256 numerator, int256 denominator ) public pure returns (int256) { require(numerator <= maxNewFixed()); require(denominator <= maxNewFixed()); require(denominator != 0); int256 convertedNumerator = newFixed(numerator); int256 convertedDenominator = newFixed(denominator); return divide(convertedNumerator, convertedDenominator); } /** * @notice Returns the integer part of a fixed point number. * @dev * Test integer(0) returns 0 * Test integer(fixed1()) returns fixed1() * Test integer(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test integer(-fixed1()) returns -fixed1() * Test integer(newFixed(-maxNewFixed())) returns -maxNewFixed()*fixed1() */ function integer(int256 x) public pure returns (int256) { return (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Returns the fractional part of a fixed point number. * In the case of a negative number the fractional is also negative. * @dev * Test fractional(0) returns 0 * Test fractional(fixed1()) returns 0 * Test fractional(fixed1()-1) returns 10^24-1 * Test fractional(-fixed1()) returns 0 * Test fractional(-fixed1()+1) returns -10^24-1 */ function fractional(int256 x) public pure returns (int256) { return x - (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Converts to positive if negative. * Due to int256 having one more negative number than positive numbers * abs(minInt256) reverts. * @dev * Test abs(0) returns 0 * Test abs(fixed1()) returns -fixed1() * Test abs(-fixed1()) returns fixed1() * Test abs(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test abs(newFixed(minNewFixed())) returns -minNewFixed()*fixed1() */ function abs(int256 x) public pure returns (int256) { if (x >= 0) { return x; } else { int256 result = -x; assert (result > 0); return result; } } /** * @notice x+y. If any operator is higher than maxFixedAdd() it * might overflow. * In solidity maxInt256 + 1 = minInt256 and viceversa. * @dev * Test add(maxFixedAdd(),maxFixedAdd()) returns maxInt256()-1 * Test add(maxFixedAdd()+1,maxFixedAdd()+1) fails * Test add(-maxFixedSub(),-maxFixedSub()) returns minInt256() * Test add(-maxFixedSub()-1,-maxFixedSub()-1) fails * Test add(maxInt256(),maxInt256()) fails * Test add(minInt256(),minInt256()) fails */ function add(int256 x, int256 y) public pure returns (int256) { int256 z = x + y; if (x > 0 && y > 0) assert(z > x && z > y); if (x < 0 && y < 0) assert(z < x && z < y); return z; } /** * @notice x-y. You can use add(x,-y) instead. * @dev Tests covered by add(x,y) */ function subtract(int256 x, int256 y) public pure returns (int256) { return add(x,-y); } /** * @notice x*y. If any of the operators is higher than maxFixedMul() it * might overflow. * @dev * Test multiply(0,0) returns 0 * Test multiply(maxFixedMul(),0) returns 0 * Test multiply(0,maxFixedMul()) returns 0 * Test multiply(maxFixedMul(),fixed1()) returns maxFixedMul() * Test multiply(fixed1(),maxFixedMul()) returns maxFixedMul() * Test all combinations of (2,-2), (2, 2.5), (2, -2.5) and (0.5, -0.5) * Test multiply(fixed1()/mulPrecision(),fixed1()*mulPrecision()) * Test multiply(maxFixedMul()-1,maxFixedMul()) equals multiply(maxFixedMul(),maxFixedMul()-1) * Test multiply(maxFixedMul(),maxFixedMul()) returns maxInt256() // Probably not to the last digits * Test multiply(maxFixedMul()+1,maxFixedMul()) fails * Test multiply(maxFixedMul(),maxFixedMul()+1) fails */ function multiply(int256 x, int256 y) public pure returns (int256) { if (x == 0 || y == 0) return 0; if (y == fixed1()) return x; if (x == fixed1()) return y; // Separate into integer and fractional parts // x = x1 + x2, y = y1 + y2 int256 x1 = integer(x) / fixed1(); int256 x2 = fractional(x); int256 y1 = integer(y) / fixed1(); int256 y2 = fractional(y); // (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2) int256 x1y1 = x1 * y1; if (x1 != 0) assert(x1y1 / x1 == y1); // Overflow x1y1 // x1y1 needs to be multiplied back by fixed1 // solium-disable-next-line mixedcase int256 fixed_x1y1 = x1y1 * fixed1(); if (x1y1 != 0) assert(fixed_x1y1 / x1y1 == fixed1()); // Overflow x1y1 * fixed1 x1y1 = fixed_x1y1; int256 x2y1 = x2 * y1; if (x2 != 0) assert(x2y1 / x2 == y1); // Overflow x2y1 int256 x1y2 = x1 * y2; if (x1 != 0) assert(x1y2 / x1 == y2); // Overflow x1y2 x2 = x2 / mulPrecision(); y2 = y2 / mulPrecision(); int256 x2y2 = x2 * y2; if (x2 != 0) assert(x2y2 / x2 == y2); // Overflow x2y2 // result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1(); int256 result = x1y1; result = add(result, x2y1); // Add checks for overflow result = add(result, x1y2); // Add checks for overflow result = add(result, x2y2); // Add checks for overflow return result; } /** * @notice 1/x * @dev * Test reciprocal(0) fails * Test reciprocal(fixed1()) returns fixed1() * Test reciprocal(fixed1()*fixed1()) returns 1 // Testing how the fractional is truncated * Test reciprocal(2*fixed1()*fixed1()) returns 0 // Testing how the fractional is truncated */ function reciprocal(int256 x) public pure returns (int256) { require(x != 0); return (fixed1()*fixed1()) / x; // Can't overflow } /** * @notice x/y. If the dividend is higher than maxFixedDiv() it * might overflow. You can use multiply(x,reciprocal(y)) instead. * There is a loss of precision on division for the lower mulPrecision() decimals. * @dev * Test divide(fixed1(),0) fails * Test divide(maxFixedDiv(),1) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,1) throws * Test divide(maxFixedDiv(),maxFixedDiv()) returns fixed1() */ function divide(int256 x, int256 y) public pure returns (int256) { if (y == fixed1()) return x; require(y != 0); require(y <= maxFixedDivisor()); return multiply(x, reciprocal(y)); } } /** * @title Blocklock * @author Brendan Asselstine * @notice A time lock with a cooldown period. When locked, the contract will remain locked until it is unlocked manually * or the lock duration expires. After the contract is unlocked, it cannot be locked until the cooldown duration expires. */ library Blocklock { using SafeMath for uint256; struct State { uint256 lockedAt; uint256 unlockedAt; uint256 lockDuration; uint256 cooldownDuration; } /** * @notice Sets the duration of the lock. This how long the lock lasts before it expires and automatically unlocks. * @param self The Blocklock state * @param lockDuration The duration, in blocks, that the lock should last. */ function setLockDuration(State storage self, uint256 lockDuration) public { require(lockDuration > 0, "Blocklock/lock-min"); self.lockDuration = lockDuration; } /** * @notice Sets the cooldown duration in blocks. This is the number of blocks that must pass before being able to * lock again. The cooldown duration begins when the lock duration expires, or when it is unlocked manually. * @param self The Blocklock state * @param cooldownDuration The duration of the cooldown, in blocks. */ function setCooldownDuration(State storage self, uint256 cooldownDuration) public { require(cooldownDuration > 0, "Blocklock/cool-min"); self.cooldownDuration = cooldownDuration; } /** * @notice Returns whether the state is locked at the given block number. * @param self The Blocklock state * @param blockNumber The current block number. */ function isLocked(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt != 0 && blockNumber >= self.lockedAt && blockNumber < endAt ); } /** * @notice Locks the state at the given block number. * @param self The Blocklock state * @param blockNumber The block number to use as the lock start time */ function lock(State storage self, uint256 blockNumber) public { require(canLock(self, blockNumber), "Blocklock/no-lock"); self.lockedAt = blockNumber; } /** * @notice Manually unlocks the lock. * @param self The Blocklock state * @param blockNumber The block number at which the lock is being unlocked. */ function unlock(State storage self, uint256 blockNumber) public { self.unlockedAt = blockNumber; } /** * @notice Returns whether the Blocklock can be locked at the given block number * @param self The Blocklock state * @param blockNumber The block number to check against * @return True if we can lock at the given block number, false otherwise. */ function canLock(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt == 0 || blockNumber >= endAt.add(self.cooldownDuration) ); } function cooldownEndAt(State storage self) internal view returns (uint256) { return lockEndAt(self).add(self.cooldownDuration); } function lockEndAt(State storage self) internal view returns (uint256) { uint256 endAt = self.lockedAt.add(self.lockDuration); // if we unlocked early if (self.unlockedAt >= self.lockedAt && self.unlockedAt < endAt) { endAt = self.unlockedAt; } return endAt; } } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Make an account an operator of the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destoys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @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. * * 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. */ 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. // 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 != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ 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"); } } /** * @dev Implementation of the {IERC777} interface. * * Largely taken from the OpenZeppelin ERC777 contract. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. * * It is important to note that no Mint events are emitted. Tokens are minted in batches * by a state change in a tree data structure, so emitting a Mint event for each user * is not possible. * */ contract PoolToken is Initializable, IERC20, IERC777 { using SafeMath for uint256; using Address for address; /** * Event emitted when a user or operator redeems tokens */ event Redeemed(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant internal TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // keccak256("ERC777Token") bytes32 constant internal TOKENS_INTERFACE_HASH = 0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054; // keccak256("ERC20Token") bytes32 constant internal ERC20_TOKENS_INTERFACE_HASH = 0xaea199e31a596269b42cdafd93407f14436db6e4cad65417994c2eb37381e05a; string internal _name; string internal _symbol; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] internal _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) internal _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) internal _operators; mapping(address => mapping(address => bool)) internal _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) internal _allowances; // The Pool that is bound to this token BasePool internal _pool; /** * @notice Initializes the PoolToken. * @param name The name of the token * @param symbol The token symbol * @param defaultOperators The default operators who are allowed to move tokens */ function init ( string memory name, string memory symbol, address[] memory defaultOperators, BasePool pool ) public initializer { require(bytes(name).length != 0, "PoolToken/name"); require(bytes(symbol).length != 0, "PoolToken/symbol"); require(address(pool) != address(0), "PoolToken/pool-zero"); _name = name; _symbol = symbol; _pool = pool; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_INTERFACE_HASH, address(this)); ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC20_TOKENS_INTERFACE_HASH, address(this)); } /** * @notice Returns the address of the Pool contract * @return The address of the pool contract */ function pool() public view returns (BasePool) { return _pool; } /** * @notice Calls the ERC777 transfer hook, and emits Redeemed and Transfer. Can only be called by the Pool contract. * @param from The address from which to redeem tokens * @param amount The amount of tokens to redeem */ function poolRedeem(address from, uint256 amount) external onlyPool { _callTokensToSend(from, from, address(0), amount, '', ''); emit Redeemed(from, from, amount, '', ''); emit Transfer(from, address(0), amount); } /** * @dev See {IERC777-name}. */ function name() public view returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev See {ERC20Detailed-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public view returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view returns (uint256) { return _pool.committedSupply(); } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address _addr) external view returns (uint256) { return _pool.committedBalanceOf(_addr); } /** * @dev See {IERC777-send}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes calldata data) external { _send(msg.sender, msg.sender, recipient, amount, data, ""); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/transfer-zero"); address from = msg.sender; _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev Allows a user to withdraw their tokens as the underlying asset. * * Also emits a {Transfer} event for ERC20 compatibility. */ function redeem(uint256 amount, bytes calldata data) external { _redeem(msg.sender, msg.sender, amount, data, ""); } /** * @dev See {IERC777-burn}. Not currently implemented. * * Also emits a {Transfer} event for ERC20 compatibility. */ function burn(uint256, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) external { require(msg.sender != operator, "PoolToken/auth-self"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[msg.sender][operator]; } else { _operators[msg.sender][operator] = true; } emit AuthorizedOperator(operator, msg.sender); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) external { require(operator != msg.sender, "PoolToken/revoke-self"); if (_defaultOperators[operator]) { _revokedDefaultOperators[msg.sender][operator] = true; } else { delete _operators[msg.sender][operator]; } emit RevokedOperator(operator, msg.sender); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external { require(isOperatorFor(msg.sender, sender), "PoolToken/not-operator"); _send(msg.sender, sender, recipient, amount, data, operatorData); } /** * @dev See {IERC777-operatorBurn}. * * Currently not supported */ function operatorBurn(address, uint256, bytes calldata, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev Allows an operator to redeem tokens for the underlying asset on behalf of a user. * * Emits {Redeemed} and {Transfer} events. */ function operatorRedeem(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(msg.sender, account), "PoolToken/not-operator"); _redeem(msg.sender, account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) external returns (bool) { address holder = msg.sender; _approve(holder, spender, value); 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, "PoolToken/negative")); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {Transfer} and {Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/to-zero"); require(holder != address(0), "PoolToken/from-zero"); address spender = msg.sender; _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "PoolToken/exceed-allow")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * Called by the associated Pool to emit `Mint` events. * @param amount The amount that was minted */ function poolMint(uint256 amount) external onlyPool { _mintEvents(address(_pool), address(_pool), amount, '', ''); } /** * Emits {Minted} and {IERC20-Transfer} events. */ function _mintEvents( address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _send( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); require(to != address(0), "PoolToken/to-zero"); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, false); } /** * @dev Redeems tokens for the underlying asset. * @param operator address operator requesting the operation * @param from address token holder address * @param amount uint256 amount of tokens to redeem * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _redeem( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _pool.withdrawCommittedDepositFrom(from, amount); emit Redeemed(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } /** * @notice Moves tokens from one user to another. Emits Sent and Transfer events. */ function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _pool.moveCommitted(from, to, amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * Approves of a token spend by a spender for a holder. * @param holder The address from which the tokens are spent * @param spender The address that is spending the tokens * @param value The amount of tokens to spend */ function _approve(address holder, address spender, uint256 value) private { require(spender != address(0), "PoolToken/from-zero"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal notLocked { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck whether to require that, if the recipient is a contract, it has registered a IERC777Recipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "PoolToken/no-recip-inter"); } } /** * @notice Requires the sender to be the pool contract */ modifier onlyPool() { require(msg.sender == address(_pool), "PoolToken/only-pool"); _; } /** * @notice Requires the contract to be unlocked */ modifier notLocked() { require(!_pool.isLocked(), "PoolToken/is-locked"); _; } } /** * @title The Pool contract * @author Brendan Asselstine * @notice This contract allows users to pool deposits into Compound and win the accrued interest in periodic draws. * Funds are immediately deposited and withdrawn from the Compound cToken contract. * Draws go through three stages: open, committed and rewarded in that order. * Only one draw is ever in the open stage. Users deposits are always added to the open draw. Funds in the open Draw are that user's open balance. * When a Draw is committed, the funds in it are moved to a user's committed total and the total committed balance of all users is updated. * When a Draw is rewarded, the gross winnings are the accrued interest since the last reward (if any). A winner is selected with their chances being * proportional to their committed balance vs the total committed balance of all users. * * * With the above in mind, there is always an open draw and possibly a committed draw. The progression is: * * Step 1: Draw 1 Open * Step 2: Draw 2 Open | Draw 1 Committed * Step 3: Draw 3 Open | Draw 2 Committed | Draw 1 Rewarded * Step 4: Draw 4 Open | Draw 3 Committed | Draw 2 Rewarded * Step 5: Draw 5 Open | Draw 4 Committed | Draw 3 Rewarded * Step X: ... */ contract BasePool is Initializable, ReentrancyGuard { using DrawManager for DrawManager.State; using SafeMath for uint256; using Roles for Roles.Role; using Blocklock for Blocklock.State; bytes32 internal constant ROLLED_OVER_ENTROPY_MAGIC_NUMBER = bytes32(uint256(1)); IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("PoolTogetherRewardListener") bytes32 constant internal REWARD_LISTENER_INTERFACE_HASH = 0x68f03b0b1a978ee238a70b362091d993343460bc1a2830ab3f708936d9f564a4; /** * Emitted when a user deposits into the Pool. * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event Deposited(address indexed sender, uint256 amount); /** * Emitted when a user deposits into the Pool and the deposit is immediately committed * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event DepositedAndCommitted(address indexed sender, uint256 amount); /** * Emitted when Sponsors have deposited into the Pool * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event SponsorshipDeposited(address indexed sender, uint256 amount); /** * Emitted when an admin has been added to the Pool. * @param admin The admin that was added */ event AdminAdded(address indexed admin); /** * Emitted when an admin has been removed from the Pool. * @param admin The admin that was removed */ event AdminRemoved(address indexed admin); /** * Emitted when a user withdraws from the pool. * @param sender The user that is withdrawing from the pool * @param amount The amount that the user withdrew */ event Withdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws their sponsorship and fees from the pool. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event SponsorshipAndFeesWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their open deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event OpenDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their committed deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event CommittedDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when an address collects a fee * @param sender The address collecting the fee * @param amount The fee amount * @param drawId The draw from which the fee was awarded */ event FeeCollected(address indexed sender, uint256 amount, uint256 drawId); /** * Emitted when a new draw is opened for deposit. * @param drawId The draw id * @param feeBeneficiary The fee beneficiary for this draw * @param secretHash The committed secret hash * @param feeFraction The fee fraction of the winnings to be given to the beneficiary */ event Opened( uint256 indexed drawId, address indexed feeBeneficiary, bytes32 secretHash, uint256 feeFraction ); /** * Emitted when a draw is committed. * @param drawId The draw id */ event Committed( uint256 indexed drawId ); /** * Emitted when a draw is rewarded. * @param drawId The draw id * @param winner The address of the winner * @param entropy The entropy used to select the winner * @param winnings The net winnings given to the winner * @param fee The fee being given to the draw beneficiary */ event Rewarded( uint256 indexed drawId, address indexed winner, bytes32 entropy, uint256 winnings, uint256 fee ); /** * Emitted when a RewardListener call fails * @param drawId The draw id * @param winner The address that one the draw * @param impl The implementation address of the RewardListener */ event RewardListenerFailed( uint256 indexed drawId, address indexed winner, address indexed impl ); /** * Emitted when the fee fraction is changed. Takes effect on the next draw. * @param feeFraction The next fee fraction encoded as a fixed point 18 decimal */ event NextFeeFractionChanged(uint256 feeFraction); /** * Emitted when the next fee beneficiary changes. Takes effect on the next draw. * @param feeBeneficiary The next fee beneficiary */ event NextFeeBeneficiaryChanged(address indexed feeBeneficiary); /** * Emitted when an admin pauses the contract */ event DepositsPaused(address indexed sender); /** * Emitted when an admin unpauses the contract */ event DepositsUnpaused(address indexed sender); /** * Emitted when the draw is rolled over in the event that the secret is forgotten. */ event RolledOver(uint256 indexed drawId); struct Draw { uint256 feeFraction; //fixed point 18 address feeBeneficiary; uint256 openedBlock; bytes32 secretHash; bytes32 entropy; address winner; uint256 netWinnings; uint256 fee; } /** * The Compound cToken that this Pool is bound to. */ ICErc20 public cToken; /** * The fee beneficiary to use for subsequent Draws. */ address public nextFeeBeneficiary; /** * The fee fraction to use for subsequent Draws. */ uint256 public nextFeeFraction; /** * The total of all balances */ uint256 public accountedBalance; /** * The total deposits and winnings for each user. */ mapping (address => uint256) internal balances; /** * A mapping of draw ids to Draw structures */ mapping(uint256 => Draw) internal draws; /** * A structure that is used to manage the user's odds of winning. */ DrawManager.State internal drawState; /** * A structure containing the administrators */ Roles.Role internal admins; /** * Whether the contract is paused */ bool public paused; Blocklock.State internal blocklock; PoolToken public poolToken; /** * @notice Initializes a new Pool contract. * @param _owner The owner of the Pool. They are able to change settings and are set as the owner of new lotteries. * @param _cToken The Compound Finance MoneyMarket contract to supply and withdraw tokens. * @param _feeFraction The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number. * @param _feeBeneficiary The address that will receive the fee fraction */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 _lockDuration, uint256 _cooldownDuration ) public initializer { require(_owner != address(0), "Pool/owner-zero"); require(_cToken != address(0), "Pool/ctoken-zero"); cToken = ICErc20(_cToken); _addAdmin(_owner); _setNextFeeFraction(_feeFraction); _setNextFeeBeneficiary(_feeBeneficiary); initBlocklock(_lockDuration, _cooldownDuration); } function setPoolToken(PoolToken _poolToken) external onlyAdmin { require(address(poolToken) == address(0), "Pool/token-was-set"); require(address(_poolToken.pool()) == address(this), "Pool/token-mismatch"); poolToken = _poolToken; } function initBlocklock(uint256 _lockDuration, uint256 _cooldownDuration) internal { blocklock.setLockDuration(_lockDuration); blocklock.setCooldownDuration(_cooldownDuration); } /** * @notice Opens a new Draw. * @param _secretHash The secret hash to commit to the Draw. */ function open(bytes32 _secretHash) internal { drawState.openNextDraw(); draws[drawState.openDrawIndex] = Draw( nextFeeFraction, nextFeeBeneficiary, block.number, _secretHash, bytes32(0), address(0), uint256(0), uint256(0) ); emit Opened( drawState.openDrawIndex, nextFeeBeneficiary, _secretHash, nextFeeFraction ); } /** * @notice Emits the Committed event for the current open draw. */ function emitCommitted() internal { uint256 drawId = currentOpenDrawId(); emit Committed(drawId); if (address(poolToken) != address(0)) { poolToken.poolMint(openSupply()); } } /** * @notice Commits the current open draw, if any, and opens the next draw using the passed hash. Really this function is only called twice: * the first after Pool contract creation and the second immediately after. * Can only be called by an admin. * May fire the Committed event, and always fires the Open event. * @param nextSecretHash The secret hash to use to open a new Draw */ function openNextDraw(bytes32 nextSecretHash) public onlyAdmin { if (currentCommittedDrawId() > 0) { require(currentCommittedDrawHasBeenRewarded(), "Pool/not-reward"); } if (currentOpenDrawId() != 0) { emitCommitted(); } open(nextSecretHash); } /** * @notice Ignores the current draw, and opens the next draw. * @dev This function will be removed once the winner selection has been decentralized. * @param nextSecretHash The hash to commit for the next draw */ function rolloverAndOpenNextDraw(bytes32 nextSecretHash) public onlyAdmin { rollover(); openNextDraw(nextSecretHash); } /** * @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash. * Can only be called by an admin. * Fires the Rewarded event, the Committed event, and the Open event. * @param nextSecretHash The secret hash to use to open a new Draw * @param lastSecret The secret to reveal to reward the current committed Draw. * @param _salt The salt that was used to conceal the secret */ function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public onlyAdmin { reward(lastSecret, _salt); openNextDraw(nextSecretHash); } /** * @notice Rewards the winner for the current committed Draw using the passed secret. * The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance. * A winner is calculated using the revealed secret. * If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings. * The draw beneficiary's balance is updated with the fee. * The accounted balance is updated to include the fee and, if there was a winner, the net winnings. * Fires the Rewarded event. * @param _secret The secret to reveal for the current committed Draw * @param _salt The salt that was used to conceal the secret */ function reward(bytes32 _secret, bytes32 _salt) public onlyAdmin onlyLocked requireCommittedNoReward nonReentrant { // require that there is a committed draw // require that the committed draw has not been rewarded uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; require(draw.secretHash == keccak256(abi.encodePacked(_secret, _salt)), "Pool/bad-secret"); // derive entropy from the revealed secret bytes32 entropy = keccak256(abi.encodePacked(_secret)); _reward(drawId, draw, entropy); } function _reward(uint256 drawId, Draw storage draw, bytes32 entropy) internal { blocklock.unlock(block.number); // Select the winner using the hash as entropy address winningAddress = calculateWinner(entropy); // Calculate the gross winnings uint256 underlyingBalance = balance(); uint256 grossWinnings; // It's possible when the APR is zero that the underlying balance will be slightly lower than the accountedBalance // due to rounding errors in the Compound contract. if (underlyingBalance > accountedBalance) { grossWinnings = capWinnings(underlyingBalance.sub(accountedBalance)); } // Calculate the beneficiary fee uint256 fee = calculateFee(draw.feeFraction, grossWinnings); // Update balance of the beneficiary balances[draw.feeBeneficiary] = balances[draw.feeBeneficiary].add(fee); // Calculate the net winnings uint256 netWinnings = grossWinnings.sub(fee); draw.winner = winningAddress; draw.netWinnings = netWinnings; draw.fee = fee; draw.entropy = entropy; // If there is a winner who is to receive non-zero winnings if (winningAddress != address(0) && netWinnings != 0) { // Updated the accounted total accountedBalance = underlyingBalance; // Update balance of the winner balances[winningAddress] = balances[winningAddress].add(netWinnings); // Enter their winnings into the open draw drawState.deposit(winningAddress, netWinnings); callRewarded(winningAddress, netWinnings, drawId); } else { // Only account for the fee accountedBalance = accountedBalance.add(fee); } emit Rewarded( drawId, winningAddress, entropy, netWinnings, fee ); emit FeeCollected(draw.feeBeneficiary, fee, drawId); } /** * @notice Calls the reward listener for the winner, if a listener exists. * @dev Checks for a listener using the ERC1820 registry. The listener is given a gas stipend of 200,000 to run the function. * The number 200,000 was selected because it's safely above the gas requirements for PoolTogether [Pod](https://github.com/pooltogether/pods) contract. * * @param winner The winner. If they have a listener registered in the ERC1820 registry it will be called. * @param netWinnings The amount that was won. * @param drawId The draw id that was won. */ function callRewarded(address winner, uint256 netWinnings, uint256 drawId) internal { address impl = ERC1820_REGISTRY.getInterfaceImplementer(winner, REWARD_LISTENER_INTERFACE_HASH); if (impl != address(0)) { (bool success,) = impl.call.gas(200000)(abi.encodeWithSignature("rewarded(address,uint256,uint256)", winner, netWinnings, drawId)); if (!success) { emit RewardListenerFailed(drawId, winner, impl); } } } /** * @notice A function that skips the reward for the committed draw id. * @dev This function will be removed once the entropy is decentralized. */ function rollover() public onlyAdmin requireCommittedNoReward { uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; draw.entropy = ROLLED_OVER_ENTROPY_MAGIC_NUMBER; emit RolledOver( drawId ); emit Rewarded( drawId, address(0), ROLLED_OVER_ENTROPY_MAGIC_NUMBER, 0, 0 ); } /** * @notice Ensures that the winnings don't overflow. Note that we can make this integer max, because the fee * is always less than zero (meaning the FixidityLib.multiply will always make the number smaller) */ function capWinnings(uint256 _grossWinnings) internal pure returns (uint256) { uint256 max = uint256(FixidityLib.maxNewFixed()); if (_grossWinnings > max) { return max; } return _grossWinnings; } /** * @notice Calculate the beneficiary fee using the passed fee fraction and gross winnings. * @param _feeFraction The fee fraction, between 0 and 1, represented as a 18 point fixed number. * @param _grossWinnings The gross winnings to take a fraction of. */ function calculateFee(uint256 _feeFraction, uint256 _grossWinnings) internal pure returns (uint256) { int256 grossWinningsFixed = FixidityLib.newFixed(int256(_grossWinnings)); // _feeFraction *must* be less than 1 ether, so it will never overflow int256 feeFixed = FixidityLib.multiply(grossWinningsFixed, FixidityLib.newFixed(int256(_feeFraction), uint8(18))); return uint256(FixidityLib.fromFixed(feeFixed)); } /** * @notice Allows a user to deposit a sponsorship amount. The deposit is transferred into the cToken. * Sponsorships allow a user to contribute to the pool without becoming eligible to win. They can withdraw their sponsorship at any time. * The deposit will immediately be added to Compound and the interest will contribute to the next draw. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositSponsorship(uint256 _amount) public unlessDepositsPaused nonReentrant { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the sponsorship amount _depositSponsorshipFrom(msg.sender, _amount); } /** * @notice Deposits the token balance for this contract as a sponsorship. * If people erroneously transfer tokens to this contract, this function will allow us to recoup those tokens as sponsorship. */ function transferBalanceToSponsorship() public unlessDepositsPaused { // Deposit the sponsorship amount _depositSponsorshipFrom(address(this), token().balanceOf(address(this))); } /** * @notice Deposits into the pool under the current open Draw. The deposit is transferred into the cToken. * Once the open draw is committed, the deposit will be added to the user's total committed balance and increase their chances of winning * proportional to the total committed balance of all users. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositPool(uint256 _amount) public requireOpenDraw unlessDepositsPaused nonReentrant notLocked { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the funds _depositPoolFrom(msg.sender, _amount); } /** * @notice Deposits sponsorship for a user * @param _spender The user who is sponsoring * @param _amount The amount they are sponsoring */ function _depositSponsorshipFrom(address _spender, uint256 _amount) internal { // Deposit the funds _depositFrom(_spender, _amount); emit SponsorshipDeposited(_spender, _amount); } /** * @notice Deposits into the pool for a user. The deposit will be open until the next draw is committed. * @param _spender The user who is depositing * @param _amount The amount the user is depositing */ function _depositPoolFrom(address _spender, uint256 _amount) internal { // Update the user's eligibility drawState.deposit(_spender, _amount); _depositFrom(_spender, _amount); emit Deposited(_spender, _amount); } /** * @notice Deposits into the pool for a user. The deposit is made part of the currently committed draw * @param _spender The user who is depositing * @param _amount The amount to deposit */ function _depositPoolFromCommitted(address _spender, uint256 _amount) internal notLocked { // Update the user's eligibility drawState.depositCommitted(_spender, _amount); _depositFrom(_spender, _amount); emit DepositedAndCommitted(_spender, _amount); } /** * @notice Deposits into the pool for a user. Updates their balance and transfers their tokens into this contract. * @param _spender The user who is depositing * @param _amount The amount they are depositing */ function _depositFrom(address _spender, uint256 _amount) internal { // Update the user's balance balances[_spender] = balances[_spender].add(_amount); // Update the total of this contract accountedBalance = accountedBalance.add(_amount); // Deposit into Compound require(token().approve(address(cToken), _amount), "Pool/approve"); require(cToken.mint(_amount) == 0, "Pool/supply"); } /** * Withdraws the given amount from the user's deposits. It first withdraws from their sponsorship, * then their open deposits, then their committed deposits. * * @param amount The amount to withdraw. */ function withdraw(uint256 amount) public nonReentrant notLocked { uint256 remainingAmount = amount; // first sponsorship uint256 sponsorshipAndFeesBalance = sponsorshipAndFeeBalanceOf(msg.sender); if (sponsorshipAndFeesBalance < remainingAmount) { withdrawSponsorshipAndFee(sponsorshipAndFeesBalance); remainingAmount = remainingAmount.sub(sponsorshipAndFeesBalance); } else { withdrawSponsorshipAndFee(remainingAmount); return; } // now pending uint256 pendingBalance = drawState.openBalanceOf(msg.sender); if (pendingBalance < remainingAmount) { _withdrawOpenDeposit(msg.sender, pendingBalance); remainingAmount = remainingAmount.sub(pendingBalance); } else { _withdrawOpenDeposit(msg.sender, remainingAmount); return; } // now committed. remainingAmount should not be greater than committed balance. _withdrawCommittedDeposit(msg.sender, remainingAmount); } /** * @notice Withdraw the sender's entire balance back to them. */ function withdraw() public nonReentrant notLocked { uint256 committedBalance = drawState.committedBalanceOf(msg.sender); uint256 balance = balances[msg.sender]; // Update their chances of winning drawState.withdraw(msg.sender); _withdraw(msg.sender, balance); if (address(poolToken) != address(0)) { poolToken.poolRedeem(msg.sender, committedBalance); } emit Withdrawn(msg.sender, balance); } /** * Withdraws only from the sender's sponsorship and fee balances * @param _amount The amount to withdraw */ function withdrawSponsorshipAndFee(uint256 _amount) public { uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender); require(_amount <= sponsorshipAndFees, "Pool/exceeds-sfee"); _withdraw(msg.sender, _amount); emit SponsorshipAndFeesWithdrawn(msg.sender, _amount); } /** * Returns the total balance of the user's sponsorship and fees * @param _sender The user whose balance should be returned */ function sponsorshipAndFeeBalanceOf(address _sender) public view returns (uint256) { return balances[_sender].sub(drawState.balanceOf(_sender)); } /** * Withdraws from the user's open deposits * @param _amount The amount to withdraw */ function withdrawOpenDeposit(uint256 _amount) public nonReentrant notLocked { _withdrawOpenDeposit(msg.sender, _amount); } function _withdrawOpenDeposit(address sender, uint256 _amount) internal { drawState.withdrawOpen(sender, _amount); _withdraw(sender, _amount); emit OpenDepositWithdrawn(sender, _amount); } /** * Withdraws from the user's committed deposits * @param _amount The amount to withdraw */ function withdrawCommittedDeposit(uint256 _amount) public nonReentrant notLocked returns (bool) { _withdrawCommittedDeposit(msg.sender, _amount); return true; } function _withdrawCommittedDeposit(address sender, uint256 _amount) internal { _withdrawCommittedDepositAndEmit(sender, _amount); if (address(poolToken) != address(0)) { poolToken.poolRedeem(sender, _amount); } } /** * Allows the associated PoolToken to withdraw for a user; useful when redeeming through the token. * @param _from The user to withdraw from * @param _amount The amount to withdraw */ function withdrawCommittedDepositFrom( address _from, uint256 _amount ) external onlyToken notLocked returns (bool) { return _withdrawCommittedDepositAndEmit(_from, _amount); } /** * A function that withdraws committed deposits for a user and emits the corresponding events. * @param _from User to withdraw for * @param _amount The amount to withdraw */ function _withdrawCommittedDepositAndEmit(address _from, uint256 _amount) internal returns (bool) { drawState.withdrawCommitted(_from, _amount); _withdraw(_from, _amount); emit CommittedDepositWithdrawn(_from, _amount); return true; } /** * @notice Allows the associated PoolToken to move committed tokens from one user to another. * @param _from The account to move tokens from * @param _to The account that is receiving the tokens * @param _amount The amount of tokens to transfer */ function moveCommitted( address _from, address _to, uint256 _amount ) external onlyToken onlyCommittedBalanceGteq(_from, _amount) notLocked returns (bool) { balances[_from] = balances[_from].sub(_amount, "move could not sub amount"); balances[_to] = balances[_to].add(_amount); drawState.withdrawCommitted(_from, _amount); drawState.depositCommitted(_to, _amount); return true; } /** * @notice Transfers tokens from the cToken contract to the sender. Updates the accounted balance. */ function _withdraw(address _sender, uint256 _amount) internal { uint256 balance = balances[_sender]; require(_amount <= balance, "Pool/no-funds"); // Update the user's balance balances[_sender] = balance.sub(_amount); // Update the total of this contract accountedBalance = accountedBalance.sub(_amount); // Withdraw from Compound and transfer require(cToken.redeemUnderlying(_amount) == 0, "Pool/redeem"); require(token().transfer(_sender, _amount), "Pool/transfer"); } /** * @notice Returns the id of the current open Draw. * @return The current open Draw id */ function currentOpenDrawId() public view returns (uint256) { return drawState.openDrawIndex; } /** * @notice Returns the id of the current committed Draw. * @return The current committed Draw id */ function currentCommittedDrawId() public view returns (uint256) { if (drawState.openDrawIndex > 1) { return drawState.openDrawIndex - 1; } else { return 0; } } /** * @notice Returns whether the current committed draw has been rewarded * @return True if the current committed draw has been rewarded, false otherwise */ function currentCommittedDrawHasBeenRewarded() internal view returns (bool) { Draw storage draw = draws[currentCommittedDrawId()]; return draw.entropy != bytes32(0); } /** * @notice Gets information for a given draw. * @param _drawId The id of the Draw to retrieve info for. * @return Fields including: * feeFraction: the fee fraction * feeBeneficiary: the beneficiary of the fee * openedBlock: The block at which the draw was opened * secretHash: The hash of the secret committed to this draw. * entropy: the entropy used to select the winner * winner: the address of the winner * netWinnings: the total winnings less the fee * fee: the fee taken by the beneficiary */ function getDraw(uint256 _drawId) public view returns ( uint256 feeFraction, address feeBeneficiary, uint256 openedBlock, bytes32 secretHash, bytes32 entropy, address winner, uint256 netWinnings, uint256 fee ) { Draw storage draw = draws[_drawId]; feeFraction = draw.feeFraction; feeBeneficiary = draw.feeBeneficiary; openedBlock = draw.openedBlock; secretHash = draw.secretHash; entropy = draw.entropy; winner = draw.winner; netWinnings = draw.netWinnings; fee = draw.fee; } /** * @notice Returns the total of the address's balance in committed Draws. That is, the total that contributes to their chances of winning. * @param _addr The address of the user * @return The total committed balance for the user */ function committedBalanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Returns the total of the address's balance in the open Draw. That is, the total that will *eventually* contribute to their chances of winning. * @param _addr The address of the user * @return The total open balance for the user */ function openBalanceOf(address _addr) external view returns (uint256) { return drawState.openBalanceOf(_addr); } /** * @notice Returns a user's total balance. This includes their sponsorships, fees, open deposits, and committed deposits. * @param _addr The address of the user to check. * @return The user's current balance. */ function totalBalanceOf(address _addr) external view returns (uint256) { return balances[_addr]; } /** * @notice Returns a user's committed balance. This is the balance of their Pool tokens. * @param _addr The address of the user to check. * @return The user's current balance. */ function balanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Calculates a winner using the passed entropy for the current committed balances. * @param _entropy The entropy to use to select the winner * @return The winning address */ function calculateWinner(bytes32 _entropy) public view returns (address) { return drawState.drawWithEntropy(_entropy); } /** * @notice Returns the total committed balance. Used to compute an address's chances of winning. * @return The total committed balance. */ function committedSupply() public view returns (uint256) { return drawState.committedSupply(); } /** * @notice Returns the total open balance. This balance is the number of tickets purchased for the open draw. * @return The total open balance */ function openSupply() public view returns (uint256) { return drawState.openSupply(); } /** * @notice Calculates the total estimated interest earned for the given number of blocks * @param _blocks The number of block that interest accrued for * @return The total estimated interest as a 18 point fixed decimal. */ function estimatedInterestRate(uint256 _blocks) public view returns (uint256) { return supplyRatePerBlock().mul(_blocks); } /** * @notice Convenience function to return the supplyRatePerBlock value from the money market contract. * @return The cToken supply rate per block */ function supplyRatePerBlock() public view returns (uint256) { return cToken.supplyRatePerBlock(); } /** * @notice Sets the beneficiary fee fraction for subsequent Draws. * Fires the NextFeeFractionChanged event. * Can only be called by an admin. * @param _feeFraction The fee fraction to use. * Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether). */ function setNextFeeFraction(uint256 _feeFraction) public onlyAdmin { _setNextFeeFraction(_feeFraction); } function _setNextFeeFraction(uint256 _feeFraction) internal { require(_feeFraction <= 1 ether, "Pool/less-1"); nextFeeFraction = _feeFraction; emit NextFeeFractionChanged(_feeFraction); } /** * @notice Sets the fee beneficiary for subsequent Draws. * Can only be called by admins. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin { _setNextFeeBeneficiary(_feeBeneficiary); } /** * @notice Sets the fee beneficiary for subsequent Draws. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function _setNextFeeBeneficiary(address _feeBeneficiary) internal { require(_feeBeneficiary != address(0), "Pool/not-zero"); nextFeeBeneficiary = _feeBeneficiary; emit NextFeeBeneficiaryChanged(_feeBeneficiary); } /** * @notice Adds an administrator. * Can only be called by administrators. * Fires the AdminAdded event. * @param _admin The address of the admin to add */ function addAdmin(address _admin) public onlyAdmin { _addAdmin(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function isAdmin(address _admin) public view returns (bool) { return admins.has(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function _addAdmin(address _admin) internal { admins.add(_admin); emit AdminAdded(_admin); } /** * @notice Removes an administrator * Can only be called by an admin. * Admins cannot remove themselves. This ensures there is always one admin. * @param _admin The address of the admin to remove */ function removeAdmin(address _admin) public onlyAdmin { require(admins.has(_admin), "Pool/no-admin"); require(_admin != msg.sender, "Pool/remove-self"); admins.remove(_admin); emit AdminRemoved(_admin); } /** * Requires that there is a committed draw that has not been rewarded. */ modifier requireCommittedNoReward() { require(currentCommittedDrawId() > 0, "Pool/committed"); require(!currentCommittedDrawHasBeenRewarded(), "Pool/already"); _; } /** * @notice Returns the token underlying the cToken. * @return An ERC20 token address */ function token() public view returns (IERC20) { return IERC20(cToken.underlying()); } /** * @notice Returns the underlying balance of this contract in the cToken. * @return The cToken underlying balance for this contract. */ function balance() public returns (uint256) { return cToken.balanceOfUnderlying(address(this)); } /** * @notice Locks the movement of tokens (essentially the committed deposits and winnings) * @dev The lock only lasts for a duration of blocks. The lock cannot be relocked until the cooldown duration completes. */ function lockTokens() public onlyAdmin { blocklock.lock(block.number); } /** * @notice Unlocks the movement of tokens (essentially the committed deposits) */ function unlockTokens() public onlyAdmin { blocklock.unlock(block.number); } /** * Pauses all deposits into the contract. This was added so that we can slowly deprecate Pools. Users can continue * to collect rewards and withdraw, but eventually the Pool will grow smaller. * * emits DepositsPaused */ function pauseDeposits() public unlessDepositsPaused onlyAdmin { paused = true; emit DepositsPaused(msg.sender); } /** * @notice Unpauses all deposits into the contract * * emits DepositsUnpaused */ function unpauseDeposits() public whenDepositsPaused onlyAdmin { paused = false; emit DepositsUnpaused(msg.sender); } /** * @notice Check if the contract is locked. * @return True if the contract is locked, false otherwise */ function isLocked() public view returns (bool) { return blocklock.isLocked(block.number); } /** * @notice Returns the block number at which the lock expires * @return The block number at which the lock expires */ function lockEndAt() public view returns (uint256) { return blocklock.lockEndAt(); } /** * @notice Check cooldown end block * @return The block number at which the cooldown ends and the contract can be re-locked */ function cooldownEndAt() public view returns (uint256) { return blocklock.cooldownEndAt(); } /** * @notice Returns whether the contract can be locked * @return True if the contract can be locked, false otherwise */ function canLock() public view returns (bool) { return blocklock.canLock(block.number); } /** * @notice Duration of the lock * @return Returns the duration of the lock in blocks. */ function lockDuration() public view returns (uint256) { return blocklock.lockDuration; } /** * @notice Returns the cooldown duration. The cooldown period starts after the Pool has been unlocked. * The Pool cannot be locked during the cooldown period. * @return The cooldown duration in blocks */ function cooldownDuration() public view returns (uint256) { return blocklock.cooldownDuration; } /** * @notice requires the pool not to be locked */ modifier notLocked() { require(!blocklock.isLocked(block.number), "Pool/locked"); _; } /** * @notice requires the pool to be locked */ modifier onlyLocked() { require(blocklock.isLocked(block.number), "Pool/unlocked"); _; } /** * @notice requires the caller to be an admin */ modifier onlyAdmin() { require(admins.has(msg.sender), "Pool/admin"); _; } /** * @notice Requires an open draw to exist */ modifier requireOpenDraw() { require(currentOpenDrawId() != 0, "Pool/no-open"); _; } /** * @notice Requires deposits to be paused */ modifier whenDepositsPaused() { require(paused, "Pool/d-not-paused"); _; } /** * @notice Requires deposits not to be paused */ modifier unlessDepositsPaused() { require(!paused, "Pool/d-paused"); _; } /** * @notice Requires the caller to be the pool token */ modifier onlyToken() { require(msg.sender == address(poolToken), "Pool/only-token"); _; } /** * @notice requires the passed user's committed balance to be greater than or equal to the passed amount * @param _from The user whose committed balance should be checked * @param _amount The minimum amount they must have */ modifier onlyCommittedBalanceGteq(address _from, uint256 _amount) { uint256 committedBalance = drawState.committedBalanceOf(_from); require(_amount <= committedBalance, "not enough funds"); _; } } contract ScdMcdMigration { SaiTubLike public tub; VatLike public vat; ManagerLike public cdpManager; JoinLike public saiJoin; JoinLike public wethJoin; JoinLike public daiJoin; constructor( address tub_, // SCD tub contract address address cdpManager_, // MCD manager contract address address saiJoin_, // MCD SAI collateral adapter contract address address wethJoin_, // MCD ETH collateral adapter contract address address daiJoin_ // MCD DAI adapter contract address ) public { tub = SaiTubLike(tub_); cdpManager = ManagerLike(cdpManager_); vat = VatLike(cdpManager.vat()); saiJoin = JoinLike(saiJoin_); wethJoin = JoinLike(wethJoin_); daiJoin = JoinLike(daiJoin_); require(wethJoin.gem() == tub.gem(), "non-matching-weth"); require(saiJoin.gem() == tub.sai(), "non-matching-sai"); tub.gov().approve(address(tub), uint(-1)); tub.skr().approve(address(tub), uint(-1)); tub.sai().approve(address(tub), uint(-1)); tub.sai().approve(address(saiJoin), uint(-1)); wethJoin.gem().approve(address(wethJoin), uint(-1)); daiJoin.dai().approve(address(daiJoin), uint(-1)); vat.hope(address(daiJoin)); } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } // Function to swap SAI to DAI // This function is to be used by users that want to get new DAI in exchange of old one (aka SAI) // wad amount has to be <= the value pending to reach the debt ceiling (the minimum between general and ilk one) function swapSaiToDai( uint wad ) external { // Get wad amount of SAI from user's wallet: saiJoin.gem().transferFrom(msg.sender, address(this), wad); // Join the SAI wad amount to the `vat`: saiJoin.join(address(this), wad); // Lock the SAI wad amount to the CDP and generate the same wad amount of DAI vat.frob(saiJoin.ilk(), address(this), address(this), address(this), toInt(wad), toInt(wad)); // Send DAI wad amount as a ERC20 token to the user's wallet daiJoin.exit(msg.sender, wad); } // Function to swap DAI to SAI // This function is to be used by users that want to get SAI in exchange of DAI // wad amount has to be <= the amount of SAI locked (and DAI generated) in the migration contract SAI CDP function swapDaiToSai( uint wad ) external { // Get wad amount of DAI from user's wallet: daiJoin.dai().transferFrom(msg.sender, address(this), wad); // Join the DAI wad amount to the vat: daiJoin.join(address(this), wad); // Payback the DAI wad amount and unlocks the same value of SAI collateral vat.frob(saiJoin.ilk(), address(this), address(this), address(this), -toInt(wad), -toInt(wad)); // Send SAI wad amount as a ERC20 token to the user's wallet saiJoin.exit(msg.sender, wad); } // Function to migrate a SCD CDP to MCD one (needs to be used via a proxy so the code can be kept simpler). Check MigrationProxyActions.sol code for usage. // In order to use migrate function, SCD CDP debtAmt needs to be <= SAI previously deposited in the SAI CDP * (100% - Collateralization Ratio) function migrate( bytes32 cup ) external returns (uint cdp) { // Get values uint debtAmt = tub.tab(cup); // CDP SAI debt uint pethAmt = tub.ink(cup); // CDP locked collateral uint ethAmt = tub.bid(pethAmt); // CDP locked collateral equiv in ETH // Take SAI out from MCD SAI CDP. For this operation is necessary to have a very low collateralization ratio // This is not actually a problem as this ilk will only be accessed by this migration contract, // which will make sure to have the amounts balanced out at the end of the execution. vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), -toInt(debtAmt), 0 ); saiJoin.exit(address(this), debtAmt); // SAI is exited as a token // Shut SAI CDP and gets WETH back tub.shut(cup); // CDP is closed using the SAI just exited and the MKR previously sent by the user (via the proxy call) tub.exit(pethAmt); // Converts PETH to WETH // Open future user's CDP in MCD cdp = cdpManager.open(wethJoin.ilk(), address(this)); // Join WETH to Adapter wethJoin.join(cdpManager.urns(cdp), ethAmt); // Lock WETH in future user's CDP and generate debt to compensate the SAI used to paid the SCD CDP (, uint rate,,,) = vat.ilks(wethJoin.ilk()); cdpManager.frob( cdp, toInt(ethAmt), toInt(mul(debtAmt, 10 ** 27) / rate + 1) // To avoid rounding issues we add an extra wei of debt ); // Move DAI generated to migration contract (to recover the used funds) cdpManager.move(cdp, address(this), mul(debtAmt, 10 ** 27)); // Re-balance MCD SAI migration contract's CDP vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), 0, -toInt(debtAmt) ); // Set ownership of CDP to the user cdpManager.give(cdp, msg.sender); } } /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @title MCDAwarePool * @author Brendan Asselstine [email protected] * @notice This contract is a Pool that is aware of the new Multi-Collateral Dai. It uses the ERC777Recipient interface to * detect if it's being transferred tickets from the old single collateral Dai (Sai) Pool. If it is, it migrates the Sai to Dai * and immediately deposits the new Dai as committed tickets for that user. We are knowingly bypassing the committed period for * users to encourage them to migrate to the MCD Pool. */ contract MCDAwarePool is BasePool, IERC777Recipient { IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; uint256 internal constant DEFAULT_LOCK_DURATION = 40; uint256 internal constant DEFAULT_COOLDOWN_DURATION = 80; /** * @notice The address of the ScdMcdMigration contract (see https://github.com/makerdao/developerguides/blob/master/mcd/upgrading-to-multi-collateral-dai/upgrading-to-multi-collateral-dai.md#direct-integration-with-smart-contracts) */ ScdMcdMigration public scdMcdMigration; /** * @notice The address of the Sai Pool contract */ MCDAwarePool public saiPool; /** * @notice Initializes the contract. * @param _owner The initial administrator of the contract * @param _cToken The Compound cToken to bind this Pool to * @param _feeFraction The fraction of the winnings to give to the beneficiary * @param _feeBeneficiary The beneficiary who receives the fee */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 lockDuration, uint256 cooldownDuration ) public initializer { super.init( _owner, _cToken, _feeFraction, _feeBeneficiary, lockDuration, cooldownDuration ); initRegistry(); initBlocklock(lockDuration, cooldownDuration); } /** * @notice Used to initialize the BasePool contract after an upgrade. Registers the MCDAwarePool with the ERC1820 registry so that it can receive tokens, and inits the block lock. */ function initMCDAwarePool(uint256 lockDuration, uint256 cooldownDuration) public { initRegistry(); if (blocklock.lockDuration == 0) { initBlocklock(lockDuration, cooldownDuration); } } function initRegistry() internal { ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) public onlyAdmin { _initMigration(_scdMcdMigration, _saiPool); } function _initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) internal { require(address(scdMcdMigration) == address(0), "Pool/init"); require(address(_scdMcdMigration) != address(0), "Pool/mig-def"); scdMcdMigration = _scdMcdMigration; saiPool = _saiPool; // may be null } /** * @notice Called by an ERC777 token when tokens are sent, transferred, or minted. If the sender is the original Sai Pool * and this pool is bound to the Dai token then it will accept the transfer, migrate the tokens, and deposit on behalf of * the sender. It will reject all other tokens. * * If there is a committed draw this function will mint the user tickets immediately, otherwise it will place them in the * open prize. This is to encourage migration. * * @param from The sender * @param amount The amount they are transferring */ function tokensReceived( address, // operator address from, address, // to address can't be anything but us because we don't implement ERC1820ImplementerInterface uint256 amount, bytes calldata, bytes calldata ) external unlessDepositsPaused { require(msg.sender == address(saiPoolToken()), "Pool/sai-only"); require(address(token()) == address(daiToken()), "Pool/not-dai"); // cash out of the Pool. This call transfers sai to this contract saiPoolToken().redeem(amount, ''); // approve of the transfer to the migration contract saiToken().approve(address(scdMcdMigration), amount); // migrate the sai to dai. The contract now has dai scdMcdMigration.swapSaiToDai(amount); if (currentCommittedDrawId() > 0) { // now deposit the dai as tickets _depositPoolFromCommitted(from, amount); } else { _depositPoolFrom(from, amount); } } /** * @notice Returns the address of the PoolSai pool token contract * @return The address of the Sai PoolToken contract */ function saiPoolToken() internal view returns (PoolToken) { if (address(saiPool) != address(0)) { return saiPool.poolToken(); } else { return PoolToken(0); } } /** * @notice Returns the address of the Sai token * @return The address of the sai token */ function saiToken() public returns (GemLike) { return scdMcdMigration.saiJoin().gem(); } /** * @notice Returns the address of the Dai token * @return The address of the Dai token. */ function daiToken() public returns (GemLike) { return scdMcdMigration.daiJoin().dai(); } }
Withdraws the given amount from the user's deposits. It first withdraws from their sponsorship, then their open deposits, then their committed deposits. amount The amount to withdraw./ first sponsorship
function withdraw(uint256 amount) public nonReentrant notLocked { uint256 remainingAmount = amount; uint256 sponsorshipAndFeesBalance = sponsorshipAndFeeBalanceOf(msg.sender); if (sponsorshipAndFeesBalance < remainingAmount) { withdrawSponsorshipAndFee(sponsorshipAndFeesBalance); remainingAmount = remainingAmount.sub(sponsorshipAndFeesBalance); withdrawSponsorshipAndFee(remainingAmount); return; } if (pendingBalance < remainingAmount) { _withdrawOpenDeposit(msg.sender, pendingBalance); remainingAmount = remainingAmount.sub(pendingBalance); _withdrawOpenDeposit(msg.sender, remainingAmount); return; } }
8,015,409
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./lib/ReEncryptionValidator.sol"; import "./lib/SignatureVerifier.sol"; import "./StakingEscrow.sol"; import "./proxy/Upgradeable.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/math/Math.sol"; /** * @title Adjudicator * @notice Supervises stakers' behavior and punishes when something's wrong. * @dev |v2.1.2| */ contract Adjudicator is Upgradeable { using SafeMath for uint256; using UmbralDeserializer for bytes; event CFragEvaluated( bytes32 indexed evaluationHash, address indexed investigator, bool correctness ); event IncorrectCFragVerdict( bytes32 indexed evaluationHash, address indexed worker, address indexed staker ); // used only for upgrading bytes32 constant RESERVED_CAPSULE_AND_CFRAG_BYTES = bytes32(0); address constant RESERVED_ADDRESS = address(0); StakingEscrow public immutable escrow; SignatureVerifier.HashAlgorithm public immutable hashAlgorithm; uint256 public immutable basePenalty; uint256 public immutable penaltyHistoryCoefficient; uint256 public immutable percentagePenaltyCoefficient; uint256 public immutable rewardCoefficient; mapping (address => uint256) public penaltyHistory; mapping (bytes32 => bool) public evaluatedCFrags; /** * @param _escrow Escrow contract * @param _hashAlgorithm Hashing algorithm * @param _basePenalty Base for the penalty calculation * @param _penaltyHistoryCoefficient Coefficient for calculating the penalty depending on the history * @param _percentagePenaltyCoefficient Coefficient for calculating the percentage penalty * @param _rewardCoefficient Coefficient for calculating the reward */ constructor( StakingEscrow _escrow, SignatureVerifier.HashAlgorithm _hashAlgorithm, uint256 _basePenalty, uint256 _penaltyHistoryCoefficient, uint256 _percentagePenaltyCoefficient, uint256 _rewardCoefficient ) { // Sanity checks. require(_escrow.secondsPerPeriod() > 0 && // This contract has an escrow, and it's not the null address. // The reward and penalty coefficients are set. _percentagePenaltyCoefficient != 0 && _rewardCoefficient != 0); escrow = _escrow; hashAlgorithm = _hashAlgorithm; basePenalty = _basePenalty; percentagePenaltyCoefficient = _percentagePenaltyCoefficient; penaltyHistoryCoefficient = _penaltyHistoryCoefficient; rewardCoefficient = _rewardCoefficient; } /** * @notice Submit proof that a worker created wrong CFrag * @param _capsuleBytes Serialized capsule * @param _cFragBytes Serialized CFrag * @param _cFragSignature Signature of CFrag by worker * @param _taskSignature Signature of task specification by Bob * @param _requesterPublicKey Bob's signing public key, also known as "stamp" * @param _workerPublicKey Worker's signing public key, also known as "stamp" * @param _workerIdentityEvidence Signature of worker's public key by worker's eth-key * @param _preComputedData Additional pre-computed data for CFrag correctness verification */ function evaluateCFrag( bytes memory _capsuleBytes, bytes memory _cFragBytes, bytes memory _cFragSignature, bytes memory _taskSignature, bytes memory _requesterPublicKey, bytes memory _workerPublicKey, bytes memory _workerIdentityEvidence, bytes memory _preComputedData ) public { // 1. Check that CFrag is not evaluated yet bytes32 evaluationHash = SignatureVerifier.hash( abi.encodePacked(_capsuleBytes, _cFragBytes), hashAlgorithm); require(!evaluatedCFrags[evaluationHash], "This CFrag has already been evaluated."); evaluatedCFrags[evaluationHash] = true; // 2. Verify correctness of re-encryption bool cFragIsCorrect = ReEncryptionValidator.validateCFrag(_capsuleBytes, _cFragBytes, _preComputedData); emit CFragEvaluated(evaluationHash, msg.sender, cFragIsCorrect); // 3. Verify associated public keys and signatures require(ReEncryptionValidator.checkSerializedCoordinates(_workerPublicKey), "Staker's public key is invalid"); require(ReEncryptionValidator.checkSerializedCoordinates(_requesterPublicKey), "Requester's public key is invalid"); UmbralDeserializer.PreComputedData memory precomp = _preComputedData.toPreComputedData(); // Verify worker's signature of CFrag require(SignatureVerifier.verify( _cFragBytes, abi.encodePacked(_cFragSignature, precomp.lostBytes[1]), _workerPublicKey, hashAlgorithm), "CFrag signature is invalid" ); // Verify worker's signature of taskSignature and that it corresponds to cfrag.proof.metadata UmbralDeserializer.CapsuleFrag memory cFrag = _cFragBytes.toCapsuleFrag(); require(SignatureVerifier.verify( _taskSignature, abi.encodePacked(cFrag.proof.metadata, precomp.lostBytes[2]), _workerPublicKey, hashAlgorithm), "Task signature is invalid" ); // Verify that _taskSignature is bob's signature of the task specification. // A task specification is: capsule + ursula pubkey + alice address + blockhash bytes32 stampXCoord; assembly { stampXCoord := mload(add(_workerPublicKey, 32)) } bytes memory stamp = abi.encodePacked(precomp.lostBytes[4], stampXCoord); require(SignatureVerifier.verify( abi.encodePacked(_capsuleBytes, stamp, _workerIdentityEvidence, precomp.alicesKeyAsAddress, bytes32(0)), abi.encodePacked(_taskSignature, precomp.lostBytes[3]), _requesterPublicKey, hashAlgorithm), "Specification signature is invalid" ); // 4. Extract worker address from stamp signature. address worker = SignatureVerifier.recover( SignatureVerifier.hashEIP191(stamp, byte(0x45)), // Currently, we use version E (0x45) of EIP191 signatures _workerIdentityEvidence); address staker = escrow.stakerFromWorker(worker); require(staker != address(0), "Worker must be related to a staker"); // 5. Check that staker can be slashed uint256 stakerValue = escrow.getAllTokens(staker); require(stakerValue > 0, "Staker has no tokens"); // 6. If CFrag was incorrect, slash staker if (!cFragIsCorrect) { (uint256 penalty, uint256 reward) = calculatePenaltyAndReward(staker, stakerValue); escrow.slashStaker(staker, penalty, msg.sender, reward); emit IncorrectCFragVerdict(evaluationHash, worker, staker); } } /** * @notice Calculate penalty to the staker and reward to the investigator * @param _staker Staker's address * @param _stakerValue Amount of tokens that belong to the staker */ function calculatePenaltyAndReward(address _staker, uint256 _stakerValue) internal returns (uint256 penalty, uint256 reward) { penalty = basePenalty.add(penaltyHistoryCoefficient.mul(penaltyHistory[_staker])); penalty = Math.min(penalty, _stakerValue.div(percentagePenaltyCoefficient)); reward = penalty.div(rewardCoefficient); // TODO add maximum condition or other overflow protection or other penalty condition (#305?) penaltyHistory[_staker] = penaltyHistory[_staker].add(1); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); bytes32 evaluationCFragHash = SignatureVerifier.hash( abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256); require(delegateGet(_testTarget, this.evaluatedCFrags.selector, evaluationCFragHash) == (evaluatedCFrags[evaluationCFragHash] ? 1 : 0)); require(delegateGet(_testTarget, this.penaltyHistory.selector, bytes32(bytes20(RESERVED_ADDRESS))) == penaltyHistory[RESERVED_ADDRESS]); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // preparation for the verifyState method bytes32 evaluationCFragHash = SignatureVerifier.hash( abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256); evaluatedCFrags[evaluationCFragHash] = true; penaltyHistory[RESERVED_ADDRESS] = 123; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./UmbralDeserializer.sol"; import "./SignatureVerifier.sol"; /** * @notice Validates re-encryption correctness. */ library ReEncryptionValidator { using UmbralDeserializer for bytes; //------------------------------// // Umbral-specific constants // //------------------------------// // See parameter `u` of `UmbralParameters` class in pyUmbral // https://github.com/nucypher/pyUmbral/blob/master/umbral/params.py uint8 public constant UMBRAL_PARAMETER_U_SIGN = 0x02; uint256 public constant UMBRAL_PARAMETER_U_XCOORD = 0x03c98795773ff1c241fc0b1cced85e80f8366581dda5c9452175ebd41385fa1f; uint256 public constant UMBRAL_PARAMETER_U_YCOORD = 0x7880ed56962d7c0ae44d6f14bb53b5fe64b31ea44a41d0316f3a598778f0f936; //------------------------------// // SECP256K1-specific constants // //------------------------------// // Base field order uint256 constant FIELD_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; // -2 mod FIELD_ORDER uint256 constant MINUS_2 = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2d; // (-1/2) mod FIELD_ORDER uint256 constant MINUS_ONE_HALF = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff7ffffe17; // /** * @notice Check correctness of re-encryption * @param _capsuleBytes Capsule * @param _cFragBytes Capsule frag * @param _precomputedBytes Additional precomputed data */ function validateCFrag( bytes memory _capsuleBytes, bytes memory _cFragBytes, bytes memory _precomputedBytes ) internal pure returns (bool) { UmbralDeserializer.Capsule memory _capsule = _capsuleBytes.toCapsule(); UmbralDeserializer.CapsuleFrag memory _cFrag = _cFragBytes.toCapsuleFrag(); UmbralDeserializer.PreComputedData memory _precomputed = _precomputedBytes.toPreComputedData(); // Extract Alice's address and check that it corresponds to the one provided address alicesAddress = SignatureVerifier.recover( _precomputed.hashedKFragValidityMessage, abi.encodePacked(_cFrag.proof.kFragSignature, _precomputed.lostBytes[0]) ); require(alicesAddress == _precomputed.alicesKeyAsAddress, "Bad KFrag signature"); // Compute proof's challenge scalar h, used in all ZKP verification equations uint256 h = computeProofChallengeScalar(_capsule, _cFrag); ////// // Verifying 1st equation: z*E == h*E_1 + E_2 ////// // Input validation: E require(checkCompressedPoint( _capsule.pointE.sign, _capsule.pointE.xCoord, _precomputed.pointEyCoord), "Precomputed Y coordinate of E doesn't correspond to compressed E point" ); // Input validation: z*E require(isOnCurve(_precomputed.pointEZxCoord, _precomputed.pointEZyCoord), "Point zE is not a valid EC point" ); require(ecmulVerify( _capsule.pointE.xCoord, // E_x _precomputed.pointEyCoord, // E_y _cFrag.proof.bnSig, // z _precomputed.pointEZxCoord, // zE_x _precomputed.pointEZyCoord), // zE_y "Precomputed z*E value is incorrect" ); // Input validation: E1 require(checkCompressedPoint( _cFrag.pointE1.sign, // E1_sign _cFrag.pointE1.xCoord, // E1_x _precomputed.pointE1yCoord), // E1_y "Precomputed Y coordinate of E1 doesn't correspond to compressed E1 point" ); // Input validation: h*E1 require(isOnCurve(_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord), "Point h*E1 is not a valid EC point" ); require(ecmulVerify( _cFrag.pointE1.xCoord, // E1_x _precomputed.pointE1yCoord, // E1_y h, _precomputed.pointE1HxCoord, // hE1_x _precomputed.pointE1HyCoord), // hE1_y "Precomputed h*E1 value is incorrect" ); // Input validation: E2 require(checkCompressedPoint( _cFrag.proof.pointE2.sign, // E2_sign _cFrag.proof.pointE2.xCoord, // E2_x _precomputed.pointE2yCoord), // E2_y "Precomputed Y coordinate of E2 doesn't correspond to compressed E2 point" ); bool equation_holds = eqAffineJacobian( [_precomputed.pointEZxCoord, _precomputed.pointEZyCoord], addAffineJacobian( [_cFrag.proof.pointE2.xCoord, _precomputed.pointE2yCoord], [_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord] ) ); if (!equation_holds){ return false; } ////// // Verifying 2nd equation: z*V == h*V_1 + V_2 ////// // Input validation: V require(checkCompressedPoint( _capsule.pointV.sign, _capsule.pointV.xCoord, _precomputed.pointVyCoord), "Precomputed Y coordinate of V doesn't correspond to compressed V point" ); // Input validation: z*V require(isOnCurve(_precomputed.pointVZxCoord, _precomputed.pointVZyCoord), "Point zV is not a valid EC point" ); require(ecmulVerify( _capsule.pointV.xCoord, // V_x _precomputed.pointVyCoord, // V_y _cFrag.proof.bnSig, // z _precomputed.pointVZxCoord, // zV_x _precomputed.pointVZyCoord), // zV_y "Precomputed z*V value is incorrect" ); // Input validation: V1 require(checkCompressedPoint( _cFrag.pointV1.sign, // V1_sign _cFrag.pointV1.xCoord, // V1_x _precomputed.pointV1yCoord), // V1_y "Precomputed Y coordinate of V1 doesn't correspond to compressed V1 point" ); // Input validation: h*V1 require(isOnCurve(_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord), "Point h*V1 is not a valid EC point" ); require(ecmulVerify( _cFrag.pointV1.xCoord, // V1_x _precomputed.pointV1yCoord, // V1_y h, _precomputed.pointV1HxCoord, // h*V1_x _precomputed.pointV1HyCoord), // h*V1_y "Precomputed h*V1 value is incorrect" ); // Input validation: V2 require(checkCompressedPoint( _cFrag.proof.pointV2.sign, // V2_sign _cFrag.proof.pointV2.xCoord, // V2_x _precomputed.pointV2yCoord), // V2_y "Precomputed Y coordinate of V2 doesn't correspond to compressed V2 point" ); equation_holds = eqAffineJacobian( [_precomputed.pointVZxCoord, _precomputed.pointVZyCoord], addAffineJacobian( [_cFrag.proof.pointV2.xCoord, _precomputed.pointV2yCoord], [_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord] ) ); if (!equation_holds){ return false; } ////// // Verifying 3rd equation: z*U == h*U_1 + U_2 ////// // We don't have to validate U since it's fixed and hard-coded // Input validation: z*U require(isOnCurve(_precomputed.pointUZxCoord, _precomputed.pointUZyCoord), "Point z*U is not a valid EC point" ); require(ecmulVerify( UMBRAL_PARAMETER_U_XCOORD, // U_x UMBRAL_PARAMETER_U_YCOORD, // U_y _cFrag.proof.bnSig, // z _precomputed.pointUZxCoord, // zU_x _precomputed.pointUZyCoord), // zU_y "Precomputed z*U value is incorrect" ); // Input validation: U1 (a.k.a. KFragCommitment) require(checkCompressedPoint( _cFrag.proof.pointKFragCommitment.sign, // U1_sign _cFrag.proof.pointKFragCommitment.xCoord, // U1_x _precomputed.pointU1yCoord), // U1_y "Precomputed Y coordinate of U1 doesn't correspond to compressed U1 point" ); // Input validation: h*U1 require(isOnCurve(_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord), "Point h*U1 is not a valid EC point" ); require(ecmulVerify( _cFrag.proof.pointKFragCommitment.xCoord, // U1_x _precomputed.pointU1yCoord, // U1_y h, _precomputed.pointU1HxCoord, // h*V1_x _precomputed.pointU1HyCoord), // h*V1_y "Precomputed h*V1 value is incorrect" ); // Input validation: U2 (a.k.a. KFragPok ("proof of knowledge")) require(checkCompressedPoint( _cFrag.proof.pointKFragPok.sign, // U2_sign _cFrag.proof.pointKFragPok.xCoord, // U2_x _precomputed.pointU2yCoord), // U2_y "Precomputed Y coordinate of U2 doesn't correspond to compressed U2 point" ); equation_holds = eqAffineJacobian( [_precomputed.pointUZxCoord, _precomputed.pointUZyCoord], addAffineJacobian( [_cFrag.proof.pointKFragPok.xCoord, _precomputed.pointU2yCoord], [_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord] ) ); return equation_holds; } function computeProofChallengeScalar( UmbralDeserializer.Capsule memory _capsule, UmbralDeserializer.CapsuleFrag memory _cFrag ) internal pure returns (uint256) { // Compute h = hash_to_bignum(e, e1, e2, v, v1, v2, u, u1, u2, metadata) bytes memory hashInput = abi.encodePacked( // Point E _capsule.pointE.sign, _capsule.pointE.xCoord, // Point E1 _cFrag.pointE1.sign, _cFrag.pointE1.xCoord, // Point E2 _cFrag.proof.pointE2.sign, _cFrag.proof.pointE2.xCoord ); hashInput = abi.encodePacked( hashInput, // Point V _capsule.pointV.sign, _capsule.pointV.xCoord, // Point V1 _cFrag.pointV1.sign, _cFrag.pointV1.xCoord, // Point V2 _cFrag.proof.pointV2.sign, _cFrag.proof.pointV2.xCoord ); hashInput = abi.encodePacked( hashInput, // Point U bytes1(UMBRAL_PARAMETER_U_SIGN), bytes32(UMBRAL_PARAMETER_U_XCOORD), // Point U1 _cFrag.proof.pointKFragCommitment.sign, _cFrag.proof.pointKFragCommitment.xCoord, // Point U2 _cFrag.proof.pointKFragPok.sign, _cFrag.proof.pointKFragPok.xCoord, // Re-encryption metadata _cFrag.proof.metadata ); uint256 h = extendedKeccakToBN(hashInput); return h; } function extendedKeccakToBN (bytes memory _data) internal pure returns (uint256) { bytes32 upper; bytes32 lower; // Umbral prepends to the data a customization string of 64-bytes. // In the case of hash_to_curvebn is 'hash_to_curvebn', padded with zeroes. bytes memory input = abi.encodePacked(bytes32("hash_to_curvebn"), bytes32(0x00), _data); (upper, lower) = (keccak256(abi.encodePacked(uint8(0x00), input)), keccak256(abi.encodePacked(uint8(0x01), input))); // Let n be the order of secp256k1's group (n = 2^256 - 0x1000003D1) // n_minus_1 = n - 1 // delta = 2^256 mod n_minus_1 uint256 delta = 0x14551231950b75fc4402da1732fc9bec0; uint256 n_minus_1 = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140; uint256 upper_half = mulmod(uint256(upper), delta, n_minus_1); return 1 + addmod(upper_half, uint256(lower), n_minus_1); } /// @notice Tests if a compressed point is valid, wrt to its corresponding Y coordinate /// @param _pointSign The sign byte from the compressed notation: 0x02 if the Y coord is even; 0x03 otherwise /// @param _pointX The X coordinate of an EC point in affine representation /// @param _pointY The Y coordinate of an EC point in affine representation /// @return true iff _pointSign and _pointX are the compressed representation of (_pointX, _pointY) function checkCompressedPoint( uint8 _pointSign, uint256 _pointX, uint256 _pointY ) internal pure returns(bool) { bool correct_sign = _pointY % 2 == _pointSign - 2; return correct_sign && isOnCurve(_pointX, _pointY); } /// @notice Tests if the given serialized coordinates represent a valid EC point /// @param _coords The concatenation of serialized X and Y coordinates /// @return true iff coordinates X and Y are a valid point function checkSerializedCoordinates(bytes memory _coords) internal pure returns(bool) { require(_coords.length == 64, "Serialized coordinates should be 64 B"); uint256 coordX; uint256 coordY; assembly { coordX := mload(add(_coords, 32)) coordY := mload(add(_coords, 64)) } return isOnCurve(coordX, coordY); } /// @notice Tests if a point is on the secp256k1 curve /// @param Px The X coordinate of an EC point in affine representation /// @param Py The Y coordinate of an EC point in affine representation /// @return true if (Px, Py) is a valid secp256k1 point; false otherwise function isOnCurve(uint256 Px, uint256 Py) internal pure returns (bool) { uint256 p = FIELD_ORDER; if (Px >= p || Py >= p){ return false; } uint256 y2 = mulmod(Py, Py, p); uint256 x3_plus_7 = addmod(mulmod(mulmod(Px, Px, p), Px, p), 7, p); return y2 == x3_plus_7; } // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/4 function ecmulVerify( uint256 x1, uint256 y1, uint256 scalar, uint256 qx, uint256 qy ) internal pure returns(bool) { uint256 curve_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; address signer = ecrecover(0, uint8(27 + (y1 % 2)), bytes32(x1), bytes32(mulmod(scalar, x1, curve_order))); address xyAddress = address(uint256(keccak256(abi.encodePacked(qx, qy))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return xyAddress == signer; } /// @notice Equality test of two points, in affine and Jacobian coordinates respectively /// @param P An EC point in affine coordinates /// @param Q An EC point in Jacobian coordinates /// @return true if P and Q represent the same point in affine coordinates; false otherwise function eqAffineJacobian( uint256[2] memory P, uint256[3] memory Q ) internal pure returns(bool){ uint256 Qz = Q[2]; if(Qz == 0){ return false; // Q is zero but P isn't. } uint256 p = FIELD_ORDER; uint256 Q_z_squared = mulmod(Qz, Qz, p); return mulmod(P[0], Q_z_squared, p) == Q[0] && mulmod(P[1], mulmod(Q_z_squared, Qz, p), p) == Q[1]; } /// @notice Adds two points in affine coordinates, with the result in Jacobian /// @dev Based on the addition formulas from http://www.hyperelliptic.org/EFD/g1p/auto-code/shortw/jacobian-0/addition/add-2001-b.op3 /// @param P An EC point in affine coordinates /// @param Q An EC point in affine coordinates /// @return R An EC point in Jacobian coordinates with the sum, represented by an array of 3 uint256 function addAffineJacobian( uint[2] memory P, uint[2] memory Q ) internal pure returns (uint[3] memory R) { uint256 p = FIELD_ORDER; uint256 a = P[0]; uint256 c = P[1]; uint256 t0 = Q[0]; uint256 t1 = Q[1]; if ((a == t0) && (c == t1)){ return doubleJacobian([a, c, 1]); } uint256 d = addmod(t1, p-c, p); // d = t1 - c uint256 b = addmod(t0, p-a, p); // b = t0 - a uint256 e = mulmod(b, b, p); // e = b^2 uint256 f = mulmod(e, b, p); // f = b^3 uint256 g = mulmod(a, e, p); R[0] = addmod(mulmod(d, d, p), p-addmod(mulmod(2, g, p), f, p), p); R[1] = addmod(mulmod(d, addmod(g, p-R[0], p), p), p-mulmod(c, f, p), p); R[2] = b; } /// @notice Point doubling in Jacobian coordinates /// @param P An EC point in Jacobian coordinates. /// @return Q An EC point in Jacobian coordinates function doubleJacobian(uint[3] memory P) internal pure returns (uint[3] memory Q) { uint256 z = P[2]; if (z == 0) return Q; uint256 p = FIELD_ORDER; uint256 x = P[0]; uint256 _2y = mulmod(2, P[1], p); uint256 _4yy = mulmod(_2y, _2y, p); uint256 s = mulmod(_4yy, x, p); uint256 m = mulmod(3, mulmod(x, x, p), p); uint256 t = addmod(mulmod(m, m, p), mulmod(MINUS_2, s, p),p); Q[0] = t; Q[1] = addmod(mulmod(m, addmod(s, p - t, p), p), mulmod(MINUS_ONE_HALF, mulmod(_4yy, _4yy, p), p), p); Q[2] = mulmod(_2y, z, p); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @notice Deserialization library for Umbral objects */ library UmbralDeserializer { struct Point { uint8 sign; uint256 xCoord; } struct Capsule { Point pointE; Point pointV; uint256 bnSig; } struct CorrectnessProof { Point pointE2; Point pointV2; Point pointKFragCommitment; Point pointKFragPok; uint256 bnSig; bytes kFragSignature; // 64 bytes bytes metadata; // any length } struct CapsuleFrag { Point pointE1; Point pointV1; bytes32 kFragId; Point pointPrecursor; CorrectnessProof proof; } struct PreComputedData { uint256 pointEyCoord; uint256 pointEZxCoord; uint256 pointEZyCoord; uint256 pointE1yCoord; uint256 pointE1HxCoord; uint256 pointE1HyCoord; uint256 pointE2yCoord; uint256 pointVyCoord; uint256 pointVZxCoord; uint256 pointVZyCoord; uint256 pointV1yCoord; uint256 pointV1HxCoord; uint256 pointV1HyCoord; uint256 pointV2yCoord; uint256 pointUZxCoord; uint256 pointUZyCoord; uint256 pointU1yCoord; uint256 pointU1HxCoord; uint256 pointU1HyCoord; uint256 pointU2yCoord; bytes32 hashedKFragValidityMessage; address alicesKeyAsAddress; bytes5 lostBytes; } uint256 constant BIGNUM_SIZE = 32; uint256 constant POINT_SIZE = 33; uint256 constant SIGNATURE_SIZE = 64; uint256 constant CAPSULE_SIZE = 2 * POINT_SIZE + BIGNUM_SIZE; uint256 constant CORRECTNESS_PROOF_SIZE = 4 * POINT_SIZE + BIGNUM_SIZE + SIGNATURE_SIZE; uint256 constant CAPSULE_FRAG_SIZE = 3 * POINT_SIZE + BIGNUM_SIZE; uint256 constant FULL_CAPSULE_FRAG_SIZE = CAPSULE_FRAG_SIZE + CORRECTNESS_PROOF_SIZE; uint256 constant PRECOMPUTED_DATA_SIZE = (20 * BIGNUM_SIZE) + 32 + 20 + 5; /** * @notice Deserialize to capsule (not activated) */ function toCapsule(bytes memory _capsuleBytes) internal pure returns (Capsule memory capsule) { require(_capsuleBytes.length == CAPSULE_SIZE); uint256 pointer = getPointer(_capsuleBytes); pointer = copyPoint(pointer, capsule.pointE); pointer = copyPoint(pointer, capsule.pointV); capsule.bnSig = uint256(getBytes32(pointer)); } /** * @notice Deserialize to correctness proof * @param _pointer Proof bytes memory pointer * @param _proofBytesLength Proof bytes length */ function toCorrectnessProof(uint256 _pointer, uint256 _proofBytesLength) internal pure returns (CorrectnessProof memory proof) { require(_proofBytesLength >= CORRECTNESS_PROOF_SIZE); _pointer = copyPoint(_pointer, proof.pointE2); _pointer = copyPoint(_pointer, proof.pointV2); _pointer = copyPoint(_pointer, proof.pointKFragCommitment); _pointer = copyPoint(_pointer, proof.pointKFragPok); proof.bnSig = uint256(getBytes32(_pointer)); _pointer += BIGNUM_SIZE; proof.kFragSignature = new bytes(SIGNATURE_SIZE); // TODO optimize, just two mload->mstore (#1500) _pointer = copyBytes(_pointer, proof.kFragSignature, SIGNATURE_SIZE); if (_proofBytesLength > CORRECTNESS_PROOF_SIZE) { proof.metadata = new bytes(_proofBytesLength - CORRECTNESS_PROOF_SIZE); copyBytes(_pointer, proof.metadata, proof.metadata.length); } } /** * @notice Deserialize to correctness proof */ function toCorrectnessProof(bytes memory _proofBytes) internal pure returns (CorrectnessProof memory proof) { uint256 pointer = getPointer(_proofBytes); return toCorrectnessProof(pointer, _proofBytes.length); } /** * @notice Deserialize to CapsuleFrag */ function toCapsuleFrag(bytes memory _cFragBytes) internal pure returns (CapsuleFrag memory cFrag) { uint256 cFragBytesLength = _cFragBytes.length; require(cFragBytesLength >= FULL_CAPSULE_FRAG_SIZE); uint256 pointer = getPointer(_cFragBytes); pointer = copyPoint(pointer, cFrag.pointE1); pointer = copyPoint(pointer, cFrag.pointV1); cFrag.kFragId = getBytes32(pointer); pointer += BIGNUM_SIZE; pointer = copyPoint(pointer, cFrag.pointPrecursor); cFrag.proof = toCorrectnessProof(pointer, cFragBytesLength - CAPSULE_FRAG_SIZE); } /** * @notice Deserialize to precomputed data */ function toPreComputedData(bytes memory _preComputedData) internal pure returns (PreComputedData memory data) { require(_preComputedData.length == PRECOMPUTED_DATA_SIZE); uint256 initial_pointer = getPointer(_preComputedData); uint256 pointer = initial_pointer; data.pointEyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointEZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointEZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointUZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointUZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.hashedKFragValidityMessage = getBytes32(pointer); pointer += 32; data.alicesKeyAsAddress = address(bytes20(getBytes32(pointer))); pointer += 20; // Lost bytes: a bytes5 variable holding the following byte values: // 0: kfrag signature recovery value v // 1: cfrag signature recovery value v // 2: metadata signature recovery value v // 3: specification signature recovery value v // 4: ursula pubkey sign byte data.lostBytes = bytes5(getBytes32(pointer)); pointer += 5; require(pointer == initial_pointer + PRECOMPUTED_DATA_SIZE); } // TODO extract to external library if needed (#1500) /** * @notice Get the memory pointer for start of array */ function getPointer(bytes memory _bytes) internal pure returns (uint256 pointer) { assembly { pointer := add(_bytes, 32) // skip array length } } /** * @notice Copy point data from memory in the pointer position */ function copyPoint(uint256 _pointer, Point memory _point) internal pure returns (uint256 resultPointer) { // TODO optimize, copy to point memory directly (#1500) uint8 temp; uint256 xCoord; assembly { temp := byte(0, mload(_pointer)) xCoord := mload(add(_pointer, 1)) } _point.sign = temp; _point.xCoord = xCoord; resultPointer = _pointer + POINT_SIZE; } /** * @notice Read 1 byte from memory in the pointer position */ function getByte(uint256 _pointer) internal pure returns (byte result) { bytes32 word; assembly { word := mload(_pointer) } result = word[0]; return result; } /** * @notice Read 32 bytes from memory in the pointer position */ function getBytes32(uint256 _pointer) internal pure returns (bytes32 result) { assembly { result := mload(_pointer) } } /** * @notice Copy bytes from the source pointer to the target array * @dev Assumes that enough memory has been allocated to store in target. * Also assumes that '_target' was the last thing that was allocated * @param _bytesPointer Source memory pointer * @param _target Target array * @param _bytesLength Number of bytes to copy */ function copyBytes(uint256 _bytesPointer, bytes memory _target, uint256 _bytesLength) internal pure returns (uint256 resultPointer) { // Exploiting the fact that '_target' was the last thing to be allocated, // we can write entire words, and just overwrite any excess. assembly { // evm operations on words let words := div(add(_bytesLength, 31), 32) let source := _bytesPointer let destination := add(_target, 32) for { let i := 0 } // start at arr + 32 -> first byte corresponds to length lt(i, words) { i := add(i, 1) } { let offset := mul(i, 32) mstore(add(destination, offset), mload(add(source, offset))) } mstore(add(_target, add(32, mload(_target))), 0) } resultPointer = _bytesPointer + _bytesLength; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @notice Library to recover address and verify signatures * @dev Simple wrapper for `ecrecover` */ library SignatureVerifier { enum HashAlgorithm {KECCAK256, SHA256, RIPEMD160} // Header for Version E as defined by EIP191. First byte ('E') is also the version bytes25 constant EIP191_VERSION_E_HEADER = "Ethereum Signed Message:\n"; /** * @notice Recover signer address from hash and signature * @param _hash 32 bytes message hash * @param _signature Signature of hash - 32 bytes r + 32 bytes s + 1 byte v (could be 0, 1, 27, 28) */ function recover(bytes32 _hash, bytes memory _signature) internal pure returns (address) { require(_signature.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } require(v == 27 || v == 28); return ecrecover(_hash, v, r, s); } /** * @notice Transform public key to address * @param _publicKey secp256k1 public key */ function toAddress(bytes memory _publicKey) internal pure returns (address) { return address(uint160(uint256(keccak256(_publicKey)))); } /** * @notice Hash using one of pre built hashing algorithm * @param _message Signed message * @param _algorithm Hashing algorithm */ function hash(bytes memory _message, HashAlgorithm _algorithm) internal pure returns (bytes32 result) { if (_algorithm == HashAlgorithm.KECCAK256) { result = keccak256(_message); } else if (_algorithm == HashAlgorithm.SHA256) { result = sha256(_message); } else { result = ripemd160(_message); } } /** * @notice Verify ECDSA signature * @dev Uses one of pre built hashing algorithm * @param _message Signed message * @param _signature Signature of message hash * @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes) * @param _algorithm Hashing algorithm */ function verify( bytes memory _message, bytes memory _signature, bytes memory _publicKey, HashAlgorithm _algorithm ) internal pure returns (bool) { require(_publicKey.length == 64); return toAddress(_publicKey) == recover(hash(_message, _algorithm), _signature); } /** * @notice Hash message according to EIP191 signature specification * @dev It always assumes Keccak256 is used as hashing algorithm * @dev Only supports version 0 and version E (0x45) * @param _message Message to sign * @param _version EIP191 version to use */ function hashEIP191( bytes memory _message, byte _version ) internal view returns (bytes32 result) { if(_version == byte(0x00)){ // Version 0: Data with intended validator address validator = address(this); return keccak256(abi.encodePacked(byte(0x19), byte(0x00), validator, _message)); } else if (_version == byte(0x45)){ // Version E: personal_sign messages uint256 length = _message.length; require(length > 0, "Empty message not allowed for version E"); // Compute text-encoded length of message uint256 digits = 0; while (length != 0) { digits++; length /= 10; } bytes memory lengthAsText = new bytes(digits); length = _message.length; uint256 index = digits - 1; while (length != 0) { lengthAsText[index--] = byte(uint8(48 + length % 10)); length /= 10; } return keccak256(abi.encodePacked(byte(0x19), EIP191_VERSION_E_HEADER, lengthAsText, _message)); } else { revert("Unsupported EIP191 version"); } } /** * @notice Verify EIP191 signature * @dev It always assumes Keccak256 is used as hashing algorithm * @dev Only supports version 0 and version E (0x45) * @param _message Signed message * @param _signature Signature of message hash * @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes) * @param _version EIP191 version to use */ function verifyEIP191( bytes memory _message, bytes memory _signature, bytes memory _publicKey, byte _version ) internal view returns (bool) { require(_publicKey.length == 64); return toAddress(_publicKey) == recover(hashEIP191(_message, _version), _signature); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../aragon/interfaces/IERC900History.sol"; import "./Issuer.sol"; import "./lib/Bits.sol"; import "./lib/Snapshot.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/token/ERC20/SafeERC20.sol"; /** * @notice PolicyManager interface */ interface PolicyManagerInterface { function secondsPerPeriod() external view returns (uint32); function register(address _node, uint16 _period) external; function migrate(address _node) external; function ping( address _node, uint16 _processedPeriod1, uint16 _processedPeriod2, uint16 _periodToSetDefault ) external; } /** * @notice Adjudicator interface */ interface AdjudicatorInterface { function rewardCoefficient() external view returns (uint32); } /** * @notice WorkLock interface */ interface WorkLockInterface { function token() external view returns (NuCypherToken); } /** * @title StakingEscrowStub * @notice Stub is used to deploy main StakingEscrow after all other contract and make some variables immutable * @dev |v1.0.0| */ contract StakingEscrowStub is Upgradeable { using AdditionalMath for uint32; NuCypherToken public immutable token; uint32 public immutable genesisSecondsPerPeriod; uint32 public immutable secondsPerPeriod; uint16 public immutable minLockedPeriods; uint256 public immutable minAllowableLockedTokens; uint256 public immutable maxAllowableLockedTokens; /** * @notice Predefines some variables for use when deploying other contracts * @param _token Token contract * @param _genesisHoursPerPeriod Size of period in hours at genesis * @param _hoursPerPeriod Size of period in hours * @param _minLockedPeriods Min amount of periods during which tokens can be locked * @param _minAllowableLockedTokens Min amount of tokens that can be locked * @param _maxAllowableLockedTokens Max amount of tokens that can be locked */ constructor( NuCypherToken _token, uint32 _genesisHoursPerPeriod, uint32 _hoursPerPeriod, uint16 _minLockedPeriods, uint256 _minAllowableLockedTokens, uint256 _maxAllowableLockedTokens ) { require(_token.totalSupply() > 0 && _hoursPerPeriod != 0 && _genesisHoursPerPeriod != 0 && _genesisHoursPerPeriod <= _hoursPerPeriod && _minLockedPeriods > 1 && _maxAllowableLockedTokens != 0); token = _token; secondsPerPeriod = _hoursPerPeriod.mul32(1 hours); genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours); minLockedPeriods = _minLockedPeriods; minAllowableLockedTokens = _minAllowableLockedTokens; maxAllowableLockedTokens = _maxAllowableLockedTokens; } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); // we have to use real values even though this is a stub require(address(delegateGet(_testTarget, this.token.selector)) == address(token)); // TODO uncomment after merging this PR #2579 // require(uint32(delegateGet(_testTarget, this.genesisSecondsPerPeriod.selector)) == genesisSecondsPerPeriod); require(uint32(delegateGet(_testTarget, this.secondsPerPeriod.selector)) == secondsPerPeriod); require(uint16(delegateGet(_testTarget, this.minLockedPeriods.selector)) == minLockedPeriods); require(delegateGet(_testTarget, this.minAllowableLockedTokens.selector) == minAllowableLockedTokens); require(delegateGet(_testTarget, this.maxAllowableLockedTokens.selector) == maxAllowableLockedTokens); } } /** * @title StakingEscrow * @notice Contract holds and locks stakers tokens. * Each staker that locks their tokens will receive some compensation * @dev |v5.7.1| */ contract StakingEscrow is Issuer, IERC900History { using AdditionalMath for uint256; using AdditionalMath for uint16; using Bits for uint256; using SafeMath for uint256; using Snapshot for uint128[]; using SafeERC20 for NuCypherToken; /** * @notice Signals that tokens were deposited * @param staker Staker address * @param value Amount deposited (in NuNits) * @param periods Number of periods tokens will be locked */ event Deposited(address indexed staker, uint256 value, uint16 periods); /** * @notice Signals that tokens were stake locked * @param staker Staker address * @param value Amount locked (in NuNits) * @param firstPeriod Starting lock period * @param periods Number of periods tokens will be locked */ event Locked(address indexed staker, uint256 value, uint16 firstPeriod, uint16 periods); /** * @notice Signals that a sub-stake was divided * @param staker Staker address * @param oldValue Old sub-stake value (in NuNits) * @param lastPeriod Final locked period of old sub-stake * @param newValue New sub-stake value (in NuNits) * @param periods Number of periods to extend sub-stake */ event Divided( address indexed staker, uint256 oldValue, uint16 lastPeriod, uint256 newValue, uint16 periods ); /** * @notice Signals that two sub-stakes were merged * @param staker Staker address * @param value1 Value of first sub-stake (in NuNits) * @param value2 Value of second sub-stake (in NuNits) * @param lastPeriod Final locked period of merged sub-stake */ event Merged(address indexed staker, uint256 value1, uint256 value2, uint16 lastPeriod); /** * @notice Signals that a sub-stake was prolonged * @param staker Staker address * @param value Value of sub-stake * @param lastPeriod Final locked period of old sub-stake * @param periods Number of periods sub-stake was extended */ event Prolonged(address indexed staker, uint256 value, uint16 lastPeriod, uint16 periods); /** * @notice Signals that tokens were withdrawn to the staker * @param staker Staker address * @param value Amount withdraws (in NuNits) */ event Withdrawn(address indexed staker, uint256 value); /** * @notice Signals that the worker associated with the staker made a commitment to next period * @param staker Staker address * @param period Period committed to * @param value Amount of tokens staked for the committed period */ event CommitmentMade(address indexed staker, uint16 indexed period, uint256 value); /** * @notice Signals that tokens were minted for previous periods * @param staker Staker address * @param period Previous period tokens minted for * @param value Amount minted (in NuNits) */ event Minted(address indexed staker, uint16 indexed period, uint256 value); /** * @notice Signals that the staker was slashed * @param staker Staker address * @param penalty Slashing penalty * @param investigator Investigator address * @param reward Value of reward provided to investigator (in NuNits) */ event Slashed(address indexed staker, uint256 penalty, address indexed investigator, uint256 reward); /** * @notice Signals that the restake parameter was activated/deactivated * @param staker Staker address * @param reStake Updated parameter value */ event ReStakeSet(address indexed staker, bool reStake); /** * @notice Signals that a worker was bonded to the staker * @param staker Staker address * @param worker Worker address * @param startPeriod Period bonding occurred */ event WorkerBonded(address indexed staker, address indexed worker, uint16 indexed startPeriod); /** * @notice Signals that the winddown parameter was activated/deactivated * @param staker Staker address * @param windDown Updated parameter value */ event WindDownSet(address indexed staker, bool windDown); /** * @notice Signals that the snapshot parameter was activated/deactivated * @param staker Staker address * @param snapshotsEnabled Updated parameter value */ event SnapshotSet(address indexed staker, bool snapshotsEnabled); /** * @notice Signals that the staker migrated their stake to the new period length * @param staker Staker address * @param period Period when migration happened */ event Migrated(address indexed staker, uint16 indexed period); /// internal event event WorkMeasurementSet(address indexed staker, bool measureWork); struct SubStakeInfo { uint16 firstPeriod; uint16 lastPeriod; uint16 unlockingDuration; uint128 lockedValue; } struct Downtime { uint16 startPeriod; uint16 endPeriod; } struct StakerInfo { uint256 value; /* * Stores periods that are committed but not yet rewarded. * In order to optimize storage, only two values are used instead of an array. * commitToNextPeriod() method invokes mint() method so there can only be two committed * periods that are not yet rewarded: the current and the next periods. */ uint16 currentCommittedPeriod; uint16 nextCommittedPeriod; uint16 lastCommittedPeriod; uint16 stub1; // former slot for lockReStakeUntilPeriod uint256 completedWork; uint16 workerStartPeriod; // period when worker was bonded address worker; uint256 flags; // uint256 to acquire whole slot and minimize operations on it uint256 reservedSlot1; uint256 reservedSlot2; uint256 reservedSlot3; uint256 reservedSlot4; uint256 reservedSlot5; Downtime[] pastDowntime; SubStakeInfo[] subStakes; uint128[] history; } // used only for upgrading uint16 internal constant RESERVED_PERIOD = 0; uint16 internal constant MAX_CHECKED_VALUES = 5; // to prevent high gas consumption in loops for slashing uint16 public constant MAX_SUB_STAKES = 30; uint16 internal constant MAX_UINT16 = 65535; // indices for flags uint8 internal constant RE_STAKE_DISABLED_INDEX = 0; uint8 internal constant WIND_DOWN_INDEX = 1; uint8 internal constant MEASURE_WORK_INDEX = 2; uint8 internal constant SNAPSHOTS_DISABLED_INDEX = 3; uint8 internal constant MIGRATED_INDEX = 4; uint16 public immutable minLockedPeriods; uint16 public immutable minWorkerPeriods; uint256 public immutable minAllowableLockedTokens; uint256 public immutable maxAllowableLockedTokens; PolicyManagerInterface public immutable policyManager; AdjudicatorInterface public immutable adjudicator; WorkLockInterface public immutable workLock; mapping (address => StakerInfo) public stakerInfo; address[] public stakers; mapping (address => address) public stakerFromWorker; mapping (uint16 => uint256) stub4; // former slot for lockedPerPeriod uint128[] public balanceHistory; address stub1; // former slot for PolicyManager address stub2; // former slot for Adjudicator address stub3; // former slot for WorkLock mapping (uint16 => uint256) _lockedPerPeriod; // only to make verifyState from previous version work, temporary // TODO remove after upgrade #2579 function lockedPerPeriod(uint16 _period) public view returns (uint256) { return _period != RESERVED_PERIOD ? _lockedPerPeriod[_period] : 111; } /** * @notice Constructor sets address of token contract and coefficients for minting * @param _token Token contract * @param _policyManager Policy Manager contract * @param _adjudicator Adjudicator contract * @param _workLock WorkLock contract. Zero address if there is no WorkLock * @param _genesisHoursPerPeriod Size of period in hours at genesis * @param _hoursPerPeriod Size of period in hours * @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays, * only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2. * See Equation 10 in Staking Protocol & Economics paper * @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier) * where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration * no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1. * See Equation 8 in Staking Protocol & Economics paper. * @param _firstPhaseTotalSupply Total supply for the first phase * @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1. * See Equation 7 in Staking Protocol & Economics paper. * @param _minLockedPeriods Min amount of periods during which tokens can be locked * @param _minAllowableLockedTokens Min amount of tokens that can be locked * @param _maxAllowableLockedTokens Max amount of tokens that can be locked * @param _minWorkerPeriods Min amount of periods while a worker can't be changed */ constructor( NuCypherToken _token, PolicyManagerInterface _policyManager, AdjudicatorInterface _adjudicator, WorkLockInterface _workLock, uint32 _genesisHoursPerPeriod, uint32 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance, uint16 _minLockedPeriods, uint256 _minAllowableLockedTokens, uint256 _maxAllowableLockedTokens, uint16 _minWorkerPeriods ) Issuer( _token, _genesisHoursPerPeriod, _hoursPerPeriod, _issuanceDecayCoefficient, _lockDurationCoefficient1, _lockDurationCoefficient2, _maximumRewardedPeriods, _firstPhaseTotalSupply, _firstPhaseMaxIssuance ) { // constant `1` in the expression `_minLockedPeriods > 1` uses to simplify the `lock` method require(_minLockedPeriods > 1 && _maxAllowableLockedTokens != 0); minLockedPeriods = _minLockedPeriods; minAllowableLockedTokens = _minAllowableLockedTokens; maxAllowableLockedTokens = _maxAllowableLockedTokens; minWorkerPeriods = _minWorkerPeriods; require((_policyManager.secondsPerPeriod() == _hoursPerPeriod * (1 hours) || _policyManager.secondsPerPeriod() == _genesisHoursPerPeriod * (1 hours)) && _adjudicator.rewardCoefficient() != 0 && (address(_workLock) == address(0) || _workLock.token() == _token)); policyManager = _policyManager; adjudicator = _adjudicator; workLock = _workLock; } /** * @dev Checks the existence of a staker in the contract */ modifier onlyStaker() { StakerInfo storage info = stakerInfo[msg.sender]; require((info.value > 0 || info.nextCommittedPeriod != 0) && info.flags.bitSet(MIGRATED_INDEX)); _; } //------------------------Main getters------------------------ /** * @notice Get all tokens belonging to the staker */ function getAllTokens(address _staker) external view returns (uint256) { return stakerInfo[_staker].value; } /** * @notice Get all flags for the staker */ function getFlags(address _staker) external view returns ( bool windDown, bool reStake, bool measureWork, bool snapshots, bool migrated ) { StakerInfo storage info = stakerInfo[_staker]; windDown = info.flags.bitSet(WIND_DOWN_INDEX); reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX); measureWork = info.flags.bitSet(MEASURE_WORK_INDEX); snapshots = !info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX); migrated = info.flags.bitSet(MIGRATED_INDEX); } /** * @notice Get the start period. Use in the calculation of the last period of the sub stake * @param _info Staker structure * @param _currentPeriod Current period */ function getStartPeriod(StakerInfo storage _info, uint16 _currentPeriod) internal view returns (uint16) { // if the next period (after current) is committed if (_info.flags.bitSet(WIND_DOWN_INDEX) && _info.nextCommittedPeriod > _currentPeriod) { return _currentPeriod + 1; } return _currentPeriod; } /** * @notice Get the last period of the sub stake * @param _subStake Sub stake structure * @param _startPeriod Pre-calculated start period */ function getLastPeriodOfSubStake(SubStakeInfo storage _subStake, uint16 _startPeriod) internal view returns (uint16) { if (_subStake.lastPeriod != 0) { return _subStake.lastPeriod; } uint32 lastPeriod = uint32(_startPeriod) + _subStake.unlockingDuration; if (lastPeriod > uint32(MAX_UINT16)) { return MAX_UINT16; } return uint16(lastPeriod); } /** * @notice Get the last period of the sub stake * @param _staker Staker * @param _index Stake index */ function getLastPeriodOfSubStake(address _staker, uint256 _index) public view returns (uint16) { StakerInfo storage info = stakerInfo[_staker]; SubStakeInfo storage subStake = info.subStakes[_index]; uint16 startPeriod = getStartPeriod(info, getCurrentPeriod()); return getLastPeriodOfSubStake(subStake, startPeriod); } /** * @notice Get the value of locked tokens for a staker in a specified period * @dev Information may be incorrect for rewarded or not committed surpassed period * @param _info Staker structure * @param _currentPeriod Current period * @param _period Next period */ function getLockedTokens(StakerInfo storage _info, uint16 _currentPeriod, uint16 _period) internal view returns (uint256 lockedValue) { lockedValue = 0; uint16 startPeriod = getStartPeriod(_info, _currentPeriod); for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.firstPeriod <= _period && getLastPeriodOfSubStake(subStake, startPeriod) >= _period) { lockedValue += subStake.lockedValue; } } } /** * @notice Get the value of locked tokens for a staker in a future period * @dev This function is used by PreallocationEscrow so its signature can't be updated. * @param _staker Staker * @param _offsetPeriods Amount of periods that will be added to the current period */ function getLockedTokens(address _staker, uint16 _offsetPeriods) external view returns (uint256 lockedValue) { StakerInfo storage info = stakerInfo[_staker]; uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod.add16(_offsetPeriods); return getLockedTokens(info, currentPeriod, nextPeriod); } /** * @notice Get the last committed staker's period * @param _staker Staker */ function getLastCommittedPeriod(address _staker) public view returns (uint16) { StakerInfo storage info = stakerInfo[_staker]; return info.nextCommittedPeriod != 0 ? info.nextCommittedPeriod : info.lastCommittedPeriod; } /** * @notice Get the value of locked tokens for active stakers in (getCurrentPeriod() + _offsetPeriods) period * as well as stakers and their locked tokens * @param _offsetPeriods Amount of periods for locked tokens calculation * @param _startIndex Start index for looking in stakers array * @param _maxStakers Max stakers for looking, if set 0 then all will be used * @return allLockedTokens Sum of locked tokens for active stakers * @return activeStakers Array of stakers and their locked tokens. Stakers addresses stored as uint256 * @dev Note that activeStakers[0] in an array of uint256, but you want addresses. Careful when used directly! */ function getActiveStakers(uint16 _offsetPeriods, uint256 _startIndex, uint256 _maxStakers) external view returns (uint256 allLockedTokens, uint256[2][] memory activeStakers) { require(_offsetPeriods > 0); uint256 endIndex = stakers.length; require(_startIndex < endIndex); if (_maxStakers != 0 && _startIndex + _maxStakers < endIndex) { endIndex = _startIndex + _maxStakers; } activeStakers = new uint256[2][](endIndex - _startIndex); allLockedTokens = 0; uint256 resultIndex = 0; uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod.add16(_offsetPeriods); for (uint256 i = _startIndex; i < endIndex; i++) { address staker = stakers[i]; StakerInfo storage info = stakerInfo[staker]; if (info.currentCommittedPeriod != currentPeriod && info.nextCommittedPeriod != currentPeriod) { continue; } uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); if (lockedTokens != 0) { activeStakers[resultIndex][0] = uint256(staker); activeStakers[resultIndex++][1] = lockedTokens; allLockedTokens += lockedTokens; } } assembly { mstore(activeStakers, resultIndex) } } /** * @notice Get worker using staker's address */ function getWorkerFromStaker(address _staker) external view returns (address) { return stakerInfo[_staker].worker; } /** * @notice Get work that completed by the staker */ function getCompletedWork(address _staker) external view returns (uint256) { return stakerInfo[_staker].completedWork; } /** * @notice Find index of downtime structure that includes specified period * @dev If specified period is outside all downtime periods, the length of the array will be returned * @param _staker Staker * @param _period Specified period number */ function findIndexOfPastDowntime(address _staker, uint16 _period) external view returns (uint256 index) { StakerInfo storage info = stakerInfo[_staker]; for (index = 0; index < info.pastDowntime.length; index++) { if (_period <= info.pastDowntime[index].endPeriod) { return index; } } } //------------------------Main methods------------------------ /** * @notice Start or stop measuring the work of a staker * @param _staker Staker * @param _measureWork Value for `measureWork` parameter * @return Work that was previously done */ function setWorkMeasurement(address _staker, bool _measureWork) external returns (uint256) { require(msg.sender == address(workLock)); StakerInfo storage info = stakerInfo[_staker]; if (info.flags.bitSet(MEASURE_WORK_INDEX) == _measureWork) { return info.completedWork; } info.flags = info.flags.toggleBit(MEASURE_WORK_INDEX); emit WorkMeasurementSet(_staker, _measureWork); return info.completedWork; } /** * @notice Bond worker * @param _worker Worker address. Must be a real address, not a contract */ function bondWorker(address _worker) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; // Specified worker is already bonded with this staker require(_worker != info.worker); uint16 currentPeriod = getCurrentPeriod(); if (info.worker != address(0)) { // If this staker had a worker ... // Check that enough time has passed to change it require(currentPeriod >= info.workerStartPeriod.add16(minWorkerPeriods)); // Remove the old relation "worker->staker" stakerFromWorker[info.worker] = address(0); } if (_worker != address(0)) { // Specified worker is already in use require(stakerFromWorker[_worker] == address(0)); // Specified worker is a staker require(stakerInfo[_worker].subStakes.length == 0 || _worker == msg.sender); // Set new worker->staker relation stakerFromWorker[_worker] = msg.sender; } // Bond new worker (or unbond if _worker == address(0)) info.worker = _worker; info.workerStartPeriod = currentPeriod; emit WorkerBonded(msg.sender, _worker, currentPeriod); } /** * @notice Set `reStake` parameter. If true then all staking rewards will be added to locked stake * @param _reStake Value for parameter */ function setReStake(bool _reStake) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(RE_STAKE_DISABLED_INDEX) == !_reStake) { return; } info.flags = info.flags.toggleBit(RE_STAKE_DISABLED_INDEX); emit ReStakeSet(msg.sender, _reStake); } /** * @notice Deposit tokens from WorkLock contract * @param _staker Staker address * @param _value Amount of tokens to deposit * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function depositFromWorkLock( address _staker, uint256 _value, uint16 _unlockingDuration ) external { require(msg.sender == address(workLock)); StakerInfo storage info = stakerInfo[_staker]; if (!info.flags.bitSet(WIND_DOWN_INDEX) && info.subStakes.length == 0) { info.flags = info.flags.toggleBit(WIND_DOWN_INDEX); emit WindDownSet(_staker, true); } // WorkLock still uses the genesis period length (24h) _unlockingDuration = recalculatePeriod(_unlockingDuration); deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration); } /** * @notice Set `windDown` parameter. * If true then stake's duration will be decreasing in each period with `commitToNextPeriod()` * @param _windDown Value for parameter */ function setWindDown(bool _windDown) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(WIND_DOWN_INDEX) == _windDown) { return; } info.flags = info.flags.toggleBit(WIND_DOWN_INDEX); emit WindDownSet(msg.sender, _windDown); // duration adjustment if next period is committed uint16 nextPeriod = getCurrentPeriod() + 1; if (info.nextCommittedPeriod != nextPeriod) { return; } // adjust sub-stakes duration for the new value of winding down parameter for (uint256 index = 0; index < info.subStakes.length; index++) { SubStakeInfo storage subStake = info.subStakes[index]; // sub-stake does not have fixed last period when winding down is disabled if (!_windDown && subStake.lastPeriod == nextPeriod) { subStake.lastPeriod = 0; subStake.unlockingDuration = 1; continue; } // this sub-stake is no longer affected by winding down parameter if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) { continue; } subStake.unlockingDuration = _windDown ? subStake.unlockingDuration - 1 : subStake.unlockingDuration + 1; if (subStake.unlockingDuration == 0) { subStake.lastPeriod = nextPeriod; } } } /** * @notice Activate/deactivate taking snapshots of balances * @param _enableSnapshots True to activate snapshots, False to deactivate */ function setSnapshots(bool _enableSnapshots) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX) == !_enableSnapshots) { return; } uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); if(_enableSnapshots){ info.history.addSnapshot(info.value); balanceHistory.addSnapshot(lastGlobalBalance + info.value); } else { info.history.addSnapshot(0); balanceHistory.addSnapshot(lastGlobalBalance - info.value); } info.flags = info.flags.toggleBit(SNAPSHOTS_DISABLED_INDEX); emit SnapshotSet(msg.sender, _enableSnapshots); } /** * @notice Adds a new snapshot to both the staker and global balance histories, * assuming the staker's balance was already changed * @param _info Reference to affected staker's struct * @param _addition Variance in balance. It can be positive or negative. */ function addSnapshot(StakerInfo storage _info, int256 _addition) internal { if(!_info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX)){ _info.history.addSnapshot(_info.value); uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); balanceHistory.addSnapshot(lastGlobalBalance.addSigned(_addition)); } } /** * @notice Implementation of the receiveApproval(address,uint256,address,bytes) method * (see NuCypherToken contract). Deposit all tokens that were approved to transfer * @param _from Staker * @param _value Amount of tokens to deposit * @param _tokenContract Token contract address * @notice (param _extraData) Amount of periods during which tokens will be unlocked when wind down is enabled */ function receiveApproval( address _from, uint256 _value, address _tokenContract, bytes calldata /* _extraData */ ) external { require(_tokenContract == address(token) && msg.sender == address(token)); // Copy first 32 bytes from _extraData, according to calldata memory layout: // // 0x00: method signature 4 bytes // 0x04: _from 32 bytes after encoding // 0x24: _value 32 bytes after encoding // 0x44: _tokenContract 32 bytes after encoding // 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter) // 0x84: _extraData length 32 bytes // 0xA4: _extraData data Length determined by previous variable // // See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples uint256 payloadSize; uint256 payload; assembly { payloadSize := calldataload(0x84) payload := calldataload(0xA4) } payload = payload >> 8*(32 - payloadSize); deposit(_from, _from, MAX_SUB_STAKES, _value, uint16(payload)); } /** * @notice Deposit tokens and create new sub-stake. Use this method to become a staker * @param _staker Staker * @param _value Amount of tokens to deposit * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function deposit(address _staker, uint256 _value, uint16 _unlockingDuration) external { deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration); } /** * @notice Deposit tokens and increase lock amount of an existing sub-stake * @dev This is preferable way to stake tokens because will be fewer active sub-stakes in the result * @param _index Index of the sub stake * @param _value Amount of tokens which will be locked */ function depositAndIncrease(uint256 _index, uint256 _value) external onlyStaker { require(_index < MAX_SUB_STAKES); deposit(msg.sender, msg.sender, _index, _value, 0); } /** * @notice Deposit tokens * @dev Specify either index and zero periods (for an existing sub-stake) * or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both * @param _staker Staker * @param _payer Owner of tokens * @param _index Index of the sub stake * @param _value Amount of tokens to deposit * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function deposit(address _staker, address _payer, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal { require(_value != 0); StakerInfo storage info = stakerInfo[_staker]; // A staker can't be a worker for another staker require(stakerFromWorker[_staker] == address(0) || stakerFromWorker[_staker] == info.worker); // initial stake of the staker if (info.subStakes.length == 0 && info.lastCommittedPeriod == 0) { stakers.push(_staker); policyManager.register(_staker, getCurrentPeriod() - 1); info.flags = info.flags.toggleBit(MIGRATED_INDEX); } require(info.flags.bitSet(MIGRATED_INDEX)); token.safeTransferFrom(_payer, address(this), _value); info.value += _value; lock(_staker, _index, _value, _unlockingDuration); addSnapshot(info, int256(_value)); if (_index >= MAX_SUB_STAKES) { emit Deposited(_staker, _value, _unlockingDuration); } else { uint16 lastPeriod = getLastPeriodOfSubStake(_staker, _index); emit Deposited(_staker, _value, lastPeriod - getCurrentPeriod()); } } /** * @notice Lock some tokens as a new sub-stake * @param _value Amount of tokens which will be locked * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function lockAndCreate(uint256 _value, uint16 _unlockingDuration) external onlyStaker { lock(msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration); } /** * @notice Increase lock amount of an existing sub-stake * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease(uint256 _index, uint256 _value) external onlyStaker { require(_index < MAX_SUB_STAKES); lock(msg.sender, _index, _value, 0); } /** * @notice Lock some tokens as a stake * @dev Specify either index and zero periods (for an existing sub-stake) * or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both * @param _staker Staker * @param _index Index of the sub stake * @param _value Amount of tokens which will be locked * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function lock(address _staker, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal { if (_index < MAX_SUB_STAKES) { require(_value > 0); } else { require(_value >= minAllowableLockedTokens && _unlockingDuration >= minLockedPeriods); } uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; StakerInfo storage info = stakerInfo[_staker]; uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); uint256 requestedLockedTokens = _value.add(lockedTokens); require(requestedLockedTokens <= info.value && requestedLockedTokens <= maxAllowableLockedTokens); // next period is committed if (info.nextCommittedPeriod == nextPeriod) { _lockedPerPeriod[nextPeriod] += _value; emit CommitmentMade(_staker, nextPeriod, _value); } // if index was provided then increase existing sub-stake if (_index < MAX_SUB_STAKES) { lockAndIncrease(info, currentPeriod, nextPeriod, _staker, _index, _value); // otherwise create new } else { lockAndCreate(info, nextPeriod, _staker, _value, _unlockingDuration); } } /** * @notice Lock some tokens as a new sub-stake * @param _info Staker structure * @param _nextPeriod Next period * @param _staker Staker * @param _value Amount of tokens which will be locked * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function lockAndCreate( StakerInfo storage _info, uint16 _nextPeriod, address _staker, uint256 _value, uint16 _unlockingDuration ) internal { uint16 duration = _unlockingDuration; // if winding down is enabled and next period is committed // then sub-stakes duration were decreased if (_info.nextCommittedPeriod == _nextPeriod && _info.flags.bitSet(WIND_DOWN_INDEX)) { duration -= 1; } saveSubStake(_info, _nextPeriod, 0, duration, _value); emit Locked(_staker, _value, _nextPeriod, _unlockingDuration); } /** * @notice Increase lock amount of an existing sub-stake * @dev Probably will be created a new sub-stake but it will be active only one period * @param _info Staker structure * @param _currentPeriod Current period * @param _nextPeriod Next period * @param _staker Staker * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease( StakerInfo storage _info, uint16 _currentPeriod, uint16 _nextPeriod, address _staker, uint256 _index, uint256 _value ) internal { SubStakeInfo storage subStake = _info.subStakes[_index]; (, uint16 lastPeriod) = checkLastPeriodOfSubStake(_info, subStake, _currentPeriod); // create temporary sub-stake for current or previous committed periods // to leave locked amount in this period unchanged if (_info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod <= _currentPeriod || _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod <= _currentPeriod) { saveSubStake(_info, subStake.firstPeriod, _currentPeriod, 0, subStake.lockedValue); } subStake.lockedValue += uint128(_value); // all new locks should start from the next period subStake.firstPeriod = _nextPeriod; emit Locked(_staker, _value, _nextPeriod, lastPeriod - _currentPeriod); } /** * @notice Checks that last period of sub-stake is greater than the current period * @param _info Staker structure * @param _subStake Sub-stake structure * @param _currentPeriod Current period * @return startPeriod Start period. Use in the calculation of the last period of the sub stake * @return lastPeriod Last period of the sub stake */ function checkLastPeriodOfSubStake( StakerInfo storage _info, SubStakeInfo storage _subStake, uint16 _currentPeriod ) internal view returns (uint16 startPeriod, uint16 lastPeriod) { startPeriod = getStartPeriod(_info, _currentPeriod); lastPeriod = getLastPeriodOfSubStake(_subStake, startPeriod); // The sub stake must be active at least in the next period require(lastPeriod > _currentPeriod); } /** * @notice Save sub stake. First tries to override inactive sub stake * @dev Inactive sub stake means that last period of sub stake has been surpassed and already rewarded * @param _info Staker structure * @param _firstPeriod First period of the sub stake * @param _lastPeriod Last period of the sub stake * @param _unlockingDuration Duration of the sub stake in periods * @param _lockedValue Amount of locked tokens */ function saveSubStake( StakerInfo storage _info, uint16 _firstPeriod, uint16 _lastPeriod, uint16 _unlockingDuration, uint256 _lockedValue ) internal { for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.lastPeriod != 0 && (_info.currentCommittedPeriod == 0 || subStake.lastPeriod < _info.currentCommittedPeriod) && (_info.nextCommittedPeriod == 0 || subStake.lastPeriod < _info.nextCommittedPeriod)) { subStake.firstPeriod = _firstPeriod; subStake.lastPeriod = _lastPeriod; subStake.unlockingDuration = _unlockingDuration; subStake.lockedValue = uint128(_lockedValue); return; } } require(_info.subStakes.length < MAX_SUB_STAKES); _info.subStakes.push(SubStakeInfo(_firstPeriod, _lastPeriod, _unlockingDuration, uint128(_lockedValue))); } /** * @notice Divide sub stake into two parts * @param _index Index of the sub stake * @param _newValue New sub stake value * @param _additionalDuration Amount of periods for extending sub stake */ function divideStake(uint256 _index, uint256 _newValue, uint16 _additionalDuration) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; require(_newValue >= minAllowableLockedTokens && _additionalDuration > 0); SubStakeInfo storage subStake = info.subStakes[_index]; uint16 currentPeriod = getCurrentPeriod(); (, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod); uint256 oldValue = subStake.lockedValue; subStake.lockedValue = uint128(oldValue.sub(_newValue)); require(subStake.lockedValue >= minAllowableLockedTokens); uint16 requestedPeriods = subStake.unlockingDuration.add16(_additionalDuration); saveSubStake(info, subStake.firstPeriod, 0, requestedPeriods, _newValue); emit Divided(msg.sender, oldValue, lastPeriod, _newValue, _additionalDuration); emit Locked(msg.sender, _newValue, subStake.firstPeriod, requestedPeriods); } /** * @notice Prolong active sub stake * @param _index Index of the sub stake * @param _additionalDuration Amount of periods for extending sub stake */ function prolongStake(uint256 _index, uint16 _additionalDuration) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; // Incorrect parameters require(_additionalDuration > 0); SubStakeInfo storage subStake = info.subStakes[_index]; uint16 currentPeriod = getCurrentPeriod(); (uint16 startPeriod, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod); subStake.unlockingDuration = subStake.unlockingDuration.add16(_additionalDuration); // if the sub stake ends in the next committed period then reset the `lastPeriod` field if (lastPeriod == startPeriod) { subStake.lastPeriod = 0; } // The extended sub stake must not be less than the minimum value require(uint32(lastPeriod - currentPeriod) + _additionalDuration >= minLockedPeriods); emit Locked(msg.sender, subStake.lockedValue, lastPeriod + 1, _additionalDuration); emit Prolonged(msg.sender, subStake.lockedValue, lastPeriod, _additionalDuration); } /** * @notice Merge two sub-stakes into one if their last periods are equal * @dev It's possible that both sub-stakes will be active after this transaction. * But only one of them will be active until next call `commitToNextPeriod` (in the next period) * @param _index1 Index of the first sub-stake * @param _index2 Index of the second sub-stake */ function mergeStake(uint256 _index1, uint256 _index2) external onlyStaker { require(_index1 != _index2); // must be different sub-stakes StakerInfo storage info = stakerInfo[msg.sender]; SubStakeInfo storage subStake1 = info.subStakes[_index1]; SubStakeInfo storage subStake2 = info.subStakes[_index2]; uint16 currentPeriod = getCurrentPeriod(); (, uint16 lastPeriod1) = checkLastPeriodOfSubStake(info, subStake1, currentPeriod); (, uint16 lastPeriod2) = checkLastPeriodOfSubStake(info, subStake2, currentPeriod); // both sub-stakes must have equal last period to be mergeable require(lastPeriod1 == lastPeriod2); emit Merged(msg.sender, subStake1.lockedValue, subStake2.lockedValue, lastPeriod1); if (subStake1.firstPeriod == subStake2.firstPeriod) { subStake1.lockedValue += subStake2.lockedValue; subStake2.lastPeriod = 1; subStake2.unlockingDuration = 0; } else if (subStake1.firstPeriod > subStake2.firstPeriod) { subStake1.lockedValue += subStake2.lockedValue; subStake2.lastPeriod = subStake1.firstPeriod - 1; subStake2.unlockingDuration = 0; } else { subStake2.lockedValue += subStake1.lockedValue; subStake1.lastPeriod = subStake2.firstPeriod - 1; subStake1.unlockingDuration = 0; } } /** * @notice Remove unused sub-stake to decrease gas cost for several methods */ function removeUnusedSubStake(uint16 _index) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; uint256 lastIndex = info.subStakes.length - 1; SubStakeInfo storage subStake = info.subStakes[_index]; require(subStake.lastPeriod != 0 && (info.currentCommittedPeriod == 0 || subStake.lastPeriod < info.currentCommittedPeriod) && (info.nextCommittedPeriod == 0 || subStake.lastPeriod < info.nextCommittedPeriod)); if (_index != lastIndex) { SubStakeInfo storage lastSubStake = info.subStakes[lastIndex]; subStake.firstPeriod = lastSubStake.firstPeriod; subStake.lastPeriod = lastSubStake.lastPeriod; subStake.unlockingDuration = lastSubStake.unlockingDuration; subStake.lockedValue = lastSubStake.lockedValue; } info.subStakes.pop(); } /** * @notice Withdraw available amount of tokens to staker * @param _value Amount of tokens to withdraw */ function withdraw(uint256 _value) external onlyStaker { uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; StakerInfo storage info = stakerInfo[msg.sender]; // the max locked tokens in most cases will be in the current period // but when the staker locks more then we should use the next period uint256 lockedTokens = Math.max(getLockedTokens(info, currentPeriod, nextPeriod), getLockedTokens(info, currentPeriod, currentPeriod)); require(_value <= info.value.sub(lockedTokens)); info.value -= _value; addSnapshot(info, - int256(_value)); token.safeTransfer(msg.sender, _value); emit Withdrawn(msg.sender, _value); // unbond worker if staker withdraws last portion of NU if (info.value == 0 && info.nextCommittedPeriod == 0 && info.worker != address(0)) { stakerFromWorker[info.worker] = address(0); info.worker = address(0); emit WorkerBonded(msg.sender, address(0), currentPeriod); } } /** * @notice Make a commitment to the next period and mint for the previous period */ function commitToNextPeriod() external isInitialized { address staker = stakerFromWorker[msg.sender]; StakerInfo storage info = stakerInfo[staker]; // Staker must have a stake to make a commitment require(info.value > 0); // Only worker with real address can make a commitment require(msg.sender == tx.origin); migrate(staker); uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; // the period has already been committed require(info.nextCommittedPeriod != nextPeriod); uint16 lastCommittedPeriod = getLastCommittedPeriod(staker); (uint16 processedPeriod1, uint16 processedPeriod2) = mint(staker); uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); require(lockedTokens > 0); _lockedPerPeriod[nextPeriod] += lockedTokens; info.currentCommittedPeriod = info.nextCommittedPeriod; info.nextCommittedPeriod = nextPeriod; decreaseSubStakesDuration(info, nextPeriod); // staker was inactive for several periods if (lastCommittedPeriod < currentPeriod) { info.pastDowntime.push(Downtime(lastCommittedPeriod + 1, currentPeriod)); } policyManager.ping(staker, processedPeriod1, processedPeriod2, nextPeriod); emit CommitmentMade(staker, nextPeriod, lockedTokens); } /** * @notice Migrate from the old period length to the new one. Can be done only once * @param _staker Staker */ function migrate(address _staker) public { StakerInfo storage info = stakerInfo[_staker]; // check that provided address is/was a staker require(info.subStakes.length != 0 || info.lastCommittedPeriod != 0); if (info.flags.bitSet(MIGRATED_INDEX)) { return; } // reset state info.currentCommittedPeriod = 0; info.nextCommittedPeriod = 0; // maintain case when no more sub-stakes and need to avoid re-registering this staker during deposit info.lastCommittedPeriod = 1; info.workerStartPeriod = recalculatePeriod(info.workerStartPeriod); delete info.pastDowntime; // recalculate all sub-stakes uint16 currentPeriod = getCurrentPeriod(); for (uint256 i = 0; i < info.subStakes.length; i++) { SubStakeInfo storage subStake = info.subStakes[i]; subStake.firstPeriod = recalculatePeriod(subStake.firstPeriod); // sub-stake has fixed last period if (subStake.lastPeriod != 0) { subStake.lastPeriod = recalculatePeriod(subStake.lastPeriod); if (subStake.lastPeriod == 0) { subStake.lastPeriod = 1; } subStake.unlockingDuration = 0; // sub-stake has no fixed ending but possible that with new period length will have } else { uint16 oldCurrentPeriod = uint16(block.timestamp / genesisSecondsPerPeriod); uint16 lastPeriod = recalculatePeriod(oldCurrentPeriod + subStake.unlockingDuration); subStake.unlockingDuration = lastPeriod - currentPeriod; if (subStake.unlockingDuration == 0) { subStake.lastPeriod = lastPeriod; } } } policyManager.migrate(_staker); info.flags = info.flags.toggleBit(MIGRATED_INDEX); emit Migrated(_staker, currentPeriod); } /** * @notice Decrease sub-stakes duration if `windDown` is enabled */ function decreaseSubStakesDuration(StakerInfo storage _info, uint16 _nextPeriod) internal { if (!_info.flags.bitSet(WIND_DOWN_INDEX)) { return; } for (uint256 index = 0; index < _info.subStakes.length; index++) { SubStakeInfo storage subStake = _info.subStakes[index]; if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) { continue; } subStake.unlockingDuration--; if (subStake.unlockingDuration == 0) { subStake.lastPeriod = _nextPeriod; } } } /** * @notice Mint tokens for previous periods if staker locked their tokens and made a commitment */ function mint() external onlyStaker { // save last committed period to the storage if both periods will be empty after minting // because we won't be able to calculate last committed period // see getLastCommittedPeriod(address) StakerInfo storage info = stakerInfo[msg.sender]; uint16 previousPeriod = getCurrentPeriod() - 1; if (info.nextCommittedPeriod <= previousPeriod && info.nextCommittedPeriod != 0) { info.lastCommittedPeriod = info.nextCommittedPeriod; } (uint16 processedPeriod1, uint16 processedPeriod2) = mint(msg.sender); if (processedPeriod1 != 0 || processedPeriod2 != 0) { policyManager.ping(msg.sender, processedPeriod1, processedPeriod2, 0); } } /** * @notice Mint tokens for previous periods if staker locked their tokens and made a commitment * @param _staker Staker * @return processedPeriod1 Processed period: currentCommittedPeriod or zero * @return processedPeriod2 Processed period: nextCommittedPeriod or zero */ function mint(address _staker) internal returns (uint16 processedPeriod1, uint16 processedPeriod2) { uint16 currentPeriod = getCurrentPeriod(); uint16 previousPeriod = currentPeriod - 1; StakerInfo storage info = stakerInfo[_staker]; if (info.nextCommittedPeriod == 0 || info.currentCommittedPeriod == 0 && info.nextCommittedPeriod > previousPeriod || info.currentCommittedPeriod > previousPeriod) { return (0, 0); } uint16 startPeriod = getStartPeriod(info, currentPeriod); uint256 reward = 0; bool reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX); if (info.currentCommittedPeriod != 0) { reward = mint(info, info.currentCommittedPeriod, currentPeriod, startPeriod, reStake); processedPeriod1 = info.currentCommittedPeriod; info.currentCommittedPeriod = 0; if (reStake) { _lockedPerPeriod[info.nextCommittedPeriod] += reward; } } if (info.nextCommittedPeriod <= previousPeriod) { reward += mint(info, info.nextCommittedPeriod, currentPeriod, startPeriod, reStake); processedPeriod2 = info.nextCommittedPeriod; info.nextCommittedPeriod = 0; } info.value += reward; if (info.flags.bitSet(MEASURE_WORK_INDEX)) { info.completedWork += reward; } addSnapshot(info, int256(reward)); emit Minted(_staker, previousPeriod, reward); } /** * @notice Calculate reward for one period * @param _info Staker structure * @param _mintingPeriod Period for minting calculation * @param _currentPeriod Current period * @param _startPeriod Pre-calculated start period */ function mint( StakerInfo storage _info, uint16 _mintingPeriod, uint16 _currentPeriod, uint16 _startPeriod, bool _reStake ) internal returns (uint256 reward) { reward = 0; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (subStake.firstPeriod <= _mintingPeriod && lastPeriod >= _mintingPeriod) { uint256 subStakeReward = mint( _currentPeriod, subStake.lockedValue, _lockedPerPeriod[_mintingPeriod], lastPeriod.sub16(_mintingPeriod)); reward += subStakeReward; if (_reStake) { subStake.lockedValue += uint128(subStakeReward); } } } return reward; } //-------------------------Slashing------------------------- /** * @notice Slash the staker's stake and reward the investigator * @param _staker Staker's address * @param _penalty Penalty * @param _investigator Investigator * @param _reward Reward for the investigator */ function slashStaker( address _staker, uint256 _penalty, address _investigator, uint256 _reward ) public isInitialized { require(msg.sender == address(adjudicator)); require(_penalty > 0); StakerInfo storage info = stakerInfo[_staker]; require(info.flags.bitSet(MIGRATED_INDEX)); if (info.value <= _penalty) { _penalty = info.value; } info.value -= _penalty; if (_reward > _penalty) { _reward = _penalty; } uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; uint16 startPeriod = getStartPeriod(info, currentPeriod); (uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex) = getLockedTokensAndShortestSubStake(info, currentPeriod, nextPeriod, startPeriod); // Decrease the stake if amount of locked tokens in the current period more than staker has uint256 lockedTokens = currentLock + currentAndNextLock; if (info.value < lockedTokens) { decreaseSubStakes(info, lockedTokens - info.value, currentPeriod, startPeriod, shortestSubStakeIndex); } // Decrease the stake if amount of locked tokens in the next period more than staker has if (nextLock > 0) { lockedTokens = nextLock + currentAndNextLock - (currentAndNextLock > info.value ? currentAndNextLock - info.value : 0); if (info.value < lockedTokens) { decreaseSubStakes(info, lockedTokens - info.value, nextPeriod, startPeriod, MAX_SUB_STAKES); } } emit Slashed(_staker, _penalty, _investigator, _reward); if (_penalty > _reward) { unMint(_penalty - _reward); } // TODO change to withdrawal pattern (#1499) if (_reward > 0) { token.safeTransfer(_investigator, _reward); } addSnapshot(info, - int256(_penalty)); } /** * @notice Get the value of locked tokens for a staker in the current and the next period * and find the shortest sub stake * @param _info Staker structure * @param _currentPeriod Current period * @param _nextPeriod Next period * @param _startPeriod Pre-calculated start period * @return currentLock Amount of tokens that locked in the current period and unlocked in the next period * @return nextLock Amount of tokens that locked in the next period and not locked in the current period * @return currentAndNextLock Amount of tokens that locked in the current period and in the next period * @return shortestSubStakeIndex Index of the shortest sub stake */ function getLockedTokensAndShortestSubStake( StakerInfo storage _info, uint16 _currentPeriod, uint16 _nextPeriod, uint16 _startPeriod ) internal view returns ( uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex ) { uint16 minDuration = MAX_UINT16; uint16 minLastPeriod = MAX_UINT16; shortestSubStakeIndex = MAX_SUB_STAKES; currentLock = 0; nextLock = 0; currentAndNextLock = 0; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (lastPeriod < subStake.firstPeriod) { continue; } if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _nextPeriod) { currentAndNextLock += subStake.lockedValue; } else if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod) { currentLock += subStake.lockedValue; } else if (subStake.firstPeriod <= _nextPeriod && lastPeriod >= _nextPeriod) { nextLock += subStake.lockedValue; } uint16 duration = lastPeriod - subStake.firstPeriod; if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod && (lastPeriod < minLastPeriod || lastPeriod == minLastPeriod && duration < minDuration)) { shortestSubStakeIndex = i; minDuration = duration; minLastPeriod = lastPeriod; } } } /** * @notice Decrease short sub stakes * @param _info Staker structure * @param _penalty Penalty rate * @param _decreasePeriod The period when the decrease begins * @param _startPeriod Pre-calculated start period * @param _shortestSubStakeIndex Index of the shortest period */ function decreaseSubStakes( StakerInfo storage _info, uint256 _penalty, uint16 _decreasePeriod, uint16 _startPeriod, uint256 _shortestSubStakeIndex ) internal { SubStakeInfo storage shortestSubStake = _info.subStakes[0]; uint16 minSubStakeLastPeriod = MAX_UINT16; uint16 minSubStakeDuration = MAX_UINT16; while(_penalty > 0) { if (_shortestSubStakeIndex < MAX_SUB_STAKES) { shortestSubStake = _info.subStakes[_shortestSubStakeIndex]; minSubStakeLastPeriod = getLastPeriodOfSubStake(shortestSubStake, _startPeriod); minSubStakeDuration = minSubStakeLastPeriod - shortestSubStake.firstPeriod; _shortestSubStakeIndex = MAX_SUB_STAKES; } else { (shortestSubStake, minSubStakeDuration, minSubStakeLastPeriod) = getShortestSubStake(_info, _decreasePeriod, _startPeriod); } if (minSubStakeDuration == MAX_UINT16) { break; } uint256 appliedPenalty = _penalty; if (_penalty < shortestSubStake.lockedValue) { shortestSubStake.lockedValue -= uint128(_penalty); saveOldSubStake(_info, shortestSubStake.firstPeriod, _penalty, _decreasePeriod); _penalty = 0; } else { shortestSubStake.lastPeriod = _decreasePeriod - 1; _penalty -= shortestSubStake.lockedValue; appliedPenalty = shortestSubStake.lockedValue; } if (_info.currentCommittedPeriod >= _decreasePeriod && _info.currentCommittedPeriod <= minSubStakeLastPeriod) { _lockedPerPeriod[_info.currentCommittedPeriod] -= appliedPenalty; } if (_info.nextCommittedPeriod >= _decreasePeriod && _info.nextCommittedPeriod <= minSubStakeLastPeriod) { _lockedPerPeriod[_info.nextCommittedPeriod] -= appliedPenalty; } } } /** * @notice Get the shortest sub stake * @param _info Staker structure * @param _currentPeriod Current period * @param _startPeriod Pre-calculated start period * @return shortestSubStake The shortest sub stake * @return minSubStakeDuration Duration of the shortest sub stake * @return minSubStakeLastPeriod Last period of the shortest sub stake */ function getShortestSubStake( StakerInfo storage _info, uint16 _currentPeriod, uint16 _startPeriod ) internal view returns ( SubStakeInfo storage shortestSubStake, uint16 minSubStakeDuration, uint16 minSubStakeLastPeriod ) { shortestSubStake = shortestSubStake; minSubStakeDuration = MAX_UINT16; minSubStakeLastPeriod = MAX_UINT16; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (lastPeriod < subStake.firstPeriod) { continue; } uint16 duration = lastPeriod - subStake.firstPeriod; if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod && (lastPeriod < minSubStakeLastPeriod || lastPeriod == minSubStakeLastPeriod && duration < minSubStakeDuration)) { shortestSubStake = subStake; minSubStakeDuration = duration; minSubStakeLastPeriod = lastPeriod; } } } /** * @notice Save the old sub stake values to prevent decreasing reward for the previous period * @dev Saving happens only if the previous period is committed * @param _info Staker structure * @param _firstPeriod First period of the old sub stake * @param _lockedValue Locked value of the old sub stake * @param _currentPeriod Current period, when the old sub stake is already unlocked */ function saveOldSubStake( StakerInfo storage _info, uint16 _firstPeriod, uint256 _lockedValue, uint16 _currentPeriod ) internal { // Check that the old sub stake should be saved bool oldCurrentCommittedPeriod = _info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod < _currentPeriod; bool oldnextCommittedPeriod = _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod < _currentPeriod; bool crosscurrentCommittedPeriod = oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= _firstPeriod; bool crossnextCommittedPeriod = oldnextCommittedPeriod && _info.nextCommittedPeriod >= _firstPeriod; if (!crosscurrentCommittedPeriod && !crossnextCommittedPeriod) { return; } // Try to find already existent proper old sub stake uint16 previousPeriod = _currentPeriod - 1; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.lastPeriod == previousPeriod && ((crosscurrentCommittedPeriod == (oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= subStake.firstPeriod)) && (crossnextCommittedPeriod == (oldnextCommittedPeriod && _info.nextCommittedPeriod >= subStake.firstPeriod)))) { subStake.lockedValue += uint128(_lockedValue); return; } } saveSubStake(_info, _firstPeriod, previousPeriod, 0, _lockedValue); } //-------------Additional getters for stakers info------------- /** * @notice Return the length of the array of stakers */ function getStakersLength() external view returns (uint256) { return stakers.length; } /** * @notice Return the length of the array of sub stakes */ function getSubStakesLength(address _staker) external view returns (uint256) { return stakerInfo[_staker].subStakes.length; } /** * @notice Return the information about sub stake */ function getSubStakeInfo(address _staker, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (SubStakeInfo) // TODO "virtual" only for tests, probably will be removed after #1512 external view virtual returns ( uint16 firstPeriod, uint16 lastPeriod, uint16 unlockingDuration, uint128 lockedValue ) { SubStakeInfo storage info = stakerInfo[_staker].subStakes[_index]; firstPeriod = info.firstPeriod; lastPeriod = info.lastPeriod; unlockingDuration = info.unlockingDuration; lockedValue = info.lockedValue; } /** * @notice Return the length of the array of past downtime */ function getPastDowntimeLength(address _staker) external view returns (uint256) { return stakerInfo[_staker].pastDowntime.length; } /** * @notice Return the information about past downtime */ function getPastDowntime(address _staker, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (Downtime) external view returns (uint16 startPeriod, uint16 endPeriod) { Downtime storage downtime = stakerInfo[_staker].pastDowntime[_index]; startPeriod = downtime.startPeriod; endPeriod = downtime.endPeriod; } //------------------ ERC900 connectors ---------------------- function totalStakedForAt(address _owner, uint256 _blockNumber) public view override returns (uint256){ return stakerInfo[_owner].history.getValueAt(_blockNumber); } function totalStakedAt(uint256 _blockNumber) public view override returns (uint256){ return balanceHistory.getValueAt(_blockNumber); } function supportsHistory() external pure override returns (bool){ return true; } //------------------------Upgradeable------------------------ /** * @dev Get StakerInfo structure by delegatecall */ function delegateGetStakerInfo(address _target, bytes32 _staker) internal returns (StakerInfo memory result) { bytes32 memoryAddress = delegateGetData(_target, this.stakerInfo.selector, 1, _staker, 0); assembly { result := memoryAddress } } /** * @dev Get SubStakeInfo structure by delegatecall */ function delegateGetSubStakeInfo(address _target, bytes32 _staker, uint256 _index) internal returns (SubStakeInfo memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getSubStakeInfo.selector, 2, _staker, bytes32(_index)); assembly { result := memoryAddress } } /** * @dev Get Downtime structure by delegatecall */ function delegateGetPastDowntime(address _target, bytes32 _staker, uint256 _index) internal returns (Downtime memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getPastDowntime.selector, 2, _staker, bytes32(_index)); assembly { result := memoryAddress } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(delegateGet(_testTarget, this.lockedPerPeriod.selector, bytes32(bytes2(RESERVED_PERIOD))) == lockedPerPeriod(RESERVED_PERIOD)); require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(0))) == stakerFromWorker[address(0)]); require(delegateGet(_testTarget, this.getStakersLength.selector) == stakers.length); if (stakers.length == 0) { return; } address stakerAddress = stakers[0]; require(address(uint160(delegateGet(_testTarget, this.stakers.selector, 0))) == stakerAddress); StakerInfo storage info = stakerInfo[stakerAddress]; bytes32 staker = bytes32(uint256(stakerAddress)); StakerInfo memory infoToCheck = delegateGetStakerInfo(_testTarget, staker); require(infoToCheck.value == info.value && infoToCheck.currentCommittedPeriod == info.currentCommittedPeriod && infoToCheck.nextCommittedPeriod == info.nextCommittedPeriod && infoToCheck.flags == info.flags && infoToCheck.lastCommittedPeriod == info.lastCommittedPeriod && infoToCheck.completedWork == info.completedWork && infoToCheck.worker == info.worker && infoToCheck.workerStartPeriod == info.workerStartPeriod); require(delegateGet(_testTarget, this.getPastDowntimeLength.selector, staker) == info.pastDowntime.length); for (uint256 i = 0; i < info.pastDowntime.length && i < MAX_CHECKED_VALUES; i++) { Downtime storage downtime = info.pastDowntime[i]; Downtime memory downtimeToCheck = delegateGetPastDowntime(_testTarget, staker, i); require(downtimeToCheck.startPeriod == downtime.startPeriod && downtimeToCheck.endPeriod == downtime.endPeriod); } require(delegateGet(_testTarget, this.getSubStakesLength.selector, staker) == info.subStakes.length); for (uint256 i = 0; i < info.subStakes.length && i < MAX_CHECKED_VALUES; i++) { SubStakeInfo storage subStakeInfo = info.subStakes[i]; SubStakeInfo memory subStakeInfoToCheck = delegateGetSubStakeInfo(_testTarget, staker, i); require(subStakeInfoToCheck.firstPeriod == subStakeInfo.firstPeriod && subStakeInfoToCheck.lastPeriod == subStakeInfo.lastPeriod && subStakeInfoToCheck.unlockingDuration == subStakeInfo.unlockingDuration && subStakeInfoToCheck.lockedValue == subStakeInfo.lockedValue); } // it's not perfect because checks not only slot value but also decoding // at least without additional functions require(delegateGet(_testTarget, this.totalStakedForAt.selector, staker, bytes32(block.number)) == totalStakedForAt(stakerAddress, block.number)); require(delegateGet(_testTarget, this.totalStakedAt.selector, bytes32(block.number)) == totalStakedAt(block.number)); if (info.worker != address(0)) { require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(uint256(info.worker)))) == stakerFromWorker[info.worker]); } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // Create fake period _lockedPerPeriod[RESERVED_PERIOD] = 111; // Create fake worker stakerFromWorker[address(0)] = address(this); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; // Minimum interface to interact with Aragon's Aggregator interface IERC900History { function totalStakedForAt(address addr, uint256 blockNumber) external view returns (uint256); function totalStakedAt(uint256 blockNumber) external view returns (uint256); function supportsHistory() external pure returns (bool); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./NuCypherToken.sol"; import "../zeppelin/math/Math.sol"; import "./proxy/Upgradeable.sol"; import "./lib/AdditionalMath.sol"; import "../zeppelin/token/ERC20/SafeERC20.sol"; /** * @title Issuer * @notice Contract for calculation of issued tokens * @dev |v3.4.1| */ abstract contract Issuer is Upgradeable { using SafeERC20 for NuCypherToken; using AdditionalMath for uint32; event Donated(address indexed sender, uint256 value); /// Issuer is initialized with a reserved reward event Initialized(uint256 reservedReward); uint128 constant MAX_UINT128 = uint128(0) - 1; NuCypherToken public immutable token; uint128 public immutable totalSupply; // d * k2 uint256 public immutable mintingCoefficient; // k1 uint256 public immutable lockDurationCoefficient1; // k2 uint256 public immutable lockDurationCoefficient2; uint32 public immutable genesisSecondsPerPeriod; uint32 public immutable secondsPerPeriod; // kmax uint16 public immutable maximumRewardedPeriods; uint256 public immutable firstPhaseMaxIssuance; uint256 public immutable firstPhaseTotalSupply; /** * Current supply is used in the minting formula and is stored to prevent different calculation * for stakers which get reward in the same period. There are two values - * supply for previous period (used in formula) and supply for current period which accumulates value * before end of period. */ uint128 public previousPeriodSupply; uint128 public currentPeriodSupply; uint16 public currentMintingPeriod; /** * @notice Constructor sets address of token contract and coefficients for minting * @dev Minting formula for one sub-stake in one period for the first phase firstPhaseMaxIssuance * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2 * @dev Minting formula for one sub-stake in one period for the second phase (totalSupply - currentSupply) / d * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2 if allLockedPeriods > maximumRewardedPeriods then allLockedPeriods = maximumRewardedPeriods * @param _token Token contract * @param _genesisHoursPerPeriod Size of period in hours at genesis * @param _hoursPerPeriod Size of period in hours * @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays, * only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2. * See Equation 10 in Staking Protocol & Economics paper * @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier) * where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration * no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1. * See Equation 8 in Staking Protocol & Economics paper. * @param _firstPhaseTotalSupply Total supply for the first phase * @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1. * See Equation 7 in Staking Protocol & Economics paper. */ constructor( NuCypherToken _token, uint32 _genesisHoursPerPeriod, uint32 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance ) { uint256 localTotalSupply = _token.totalSupply(); require(localTotalSupply > 0 && _issuanceDecayCoefficient != 0 && _hoursPerPeriod != 0 && _genesisHoursPerPeriod != 0 && _genesisHoursPerPeriod <= _hoursPerPeriod && _lockDurationCoefficient1 != 0 && _lockDurationCoefficient2 != 0 && _maximumRewardedPeriods != 0); require(localTotalSupply <= uint256(MAX_UINT128), "Token contract has supply more than supported"); uint256 maxLockDurationCoefficient = _maximumRewardedPeriods + _lockDurationCoefficient1; uint256 localMintingCoefficient = _issuanceDecayCoefficient * _lockDurationCoefficient2; require(maxLockDurationCoefficient > _maximumRewardedPeriods && localMintingCoefficient / _issuanceDecayCoefficient == _lockDurationCoefficient2 && // worst case for `totalLockedValue * d * k2`, when totalLockedValue == totalSupply localTotalSupply * localMintingCoefficient / localTotalSupply == localMintingCoefficient && // worst case for `(totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax))`, // when currentSupply == 0, lockedValue == totalSupply localTotalSupply * localTotalSupply * maxLockDurationCoefficient / localTotalSupply / localTotalSupply == maxLockDurationCoefficient, "Specified parameters cause overflow"); require(maxLockDurationCoefficient <= _lockDurationCoefficient2, "Resulting locking duration coefficient must be less than 1"); require(_firstPhaseTotalSupply <= localTotalSupply, "Too many tokens for the first phase"); require(_firstPhaseMaxIssuance <= _firstPhaseTotalSupply, "Reward for the first phase is too high"); token = _token; secondsPerPeriod = _hoursPerPeriod.mul32(1 hours); genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours); lockDurationCoefficient1 = _lockDurationCoefficient1; lockDurationCoefficient2 = _lockDurationCoefficient2; maximumRewardedPeriods = _maximumRewardedPeriods; firstPhaseTotalSupply = _firstPhaseTotalSupply; firstPhaseMaxIssuance = _firstPhaseMaxIssuance; totalSupply = uint128(localTotalSupply); mintingCoefficient = localMintingCoefficient; } /** * @dev Checks contract initialization */ modifier isInitialized() { require(currentMintingPeriod != 0); _; } /** * @return Number of current period */ function getCurrentPeriod() public view returns (uint16) { return uint16(block.timestamp / secondsPerPeriod); } /** * @return Recalculate period value using new basis */ function recalculatePeriod(uint16 _period) internal view returns (uint16) { return uint16(uint256(_period) * genesisSecondsPerPeriod / secondsPerPeriod); } /** * @notice Initialize reserved tokens for reward */ function initialize(uint256 _reservedReward, address _sourceOfFunds) external onlyOwner { require(currentMintingPeriod == 0); // Reserved reward must be sufficient for at least one period of the first phase require(firstPhaseMaxIssuance <= _reservedReward); currentMintingPeriod = getCurrentPeriod(); currentPeriodSupply = totalSupply - uint128(_reservedReward); previousPeriodSupply = currentPeriodSupply; token.safeTransferFrom(_sourceOfFunds, address(this), _reservedReward); emit Initialized(_reservedReward); } /** * @notice Function to mint tokens for one period. * @param _currentPeriod Current period number. * @param _lockedValue The amount of tokens that were locked by user in specified period. * @param _totalLockedValue The amount of tokens that were locked by all users in specified period. * @param _allLockedPeriods The max amount of periods during which tokens will be locked after specified period. * @return amount Amount of minted tokens. */ function mint( uint16 _currentPeriod, uint256 _lockedValue, uint256 _totalLockedValue, uint16 _allLockedPeriods ) internal returns (uint256 amount) { if (currentPeriodSupply == totalSupply) { return 0; } if (_currentPeriod > currentMintingPeriod) { previousPeriodSupply = currentPeriodSupply; currentMintingPeriod = _currentPeriod; } uint256 currentReward; uint256 coefficient; // first phase // firstPhaseMaxIssuance * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * k2) if (previousPeriodSupply + firstPhaseMaxIssuance <= firstPhaseTotalSupply) { currentReward = firstPhaseMaxIssuance; coefficient = lockDurationCoefficient2; // second phase // (totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * d * k2) } else { currentReward = totalSupply - previousPeriodSupply; coefficient = mintingCoefficient; } uint256 allLockedPeriods = AdditionalMath.min16(_allLockedPeriods, maximumRewardedPeriods) + lockDurationCoefficient1; amount = (uint256(currentReward) * _lockedValue * allLockedPeriods) / (_totalLockedValue * coefficient); // rounding the last reward uint256 maxReward = getReservedReward(); if (amount == 0) { amount = 1; } else if (amount > maxReward) { amount = maxReward; } currentPeriodSupply += uint128(amount); } /** * @notice Return tokens for future minting * @param _amount Amount of tokens */ function unMint(uint256 _amount) internal { previousPeriodSupply -= uint128(_amount); currentPeriodSupply -= uint128(_amount); } /** * @notice Donate sender's tokens. Amount of tokens will be returned for future minting * @param _value Amount to donate */ function donate(uint256 _value) external isInitialized { token.safeTransferFrom(msg.sender, address(this), _value); unMint(_value); emit Donated(msg.sender, _value); } /** * @notice Returns the number of tokens that can be minted */ function getReservedReward() public view returns (uint256) { return totalSupply - currentPeriodSupply; } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(uint16(delegateGet(_testTarget, this.currentMintingPeriod.selector)) == currentMintingPeriod); require(uint128(delegateGet(_testTarget, this.previousPeriodSupply.selector)) == previousPeriodSupply); require(uint128(delegateGet(_testTarget, this.currentPeriodSupply.selector)) == currentPeriodSupply); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // recalculate currentMintingPeriod if needed if (currentMintingPeriod > getCurrentPeriod()) { currentMintingPeriod = recalculatePeriod(currentMintingPeriod); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/token/ERC20/ERC20.sol"; import "../zeppelin/token/ERC20/ERC20Detailed.sol"; /** * @title NuCypherToken * @notice ERC20 token * @dev Optional approveAndCall() functionality to notify a contract if an approve() has occurred. */ contract NuCypherToken is ERC20, ERC20Detailed('NuCypher', 'NU', 18) { /** * @notice Set amount of tokens * @param _totalSupplyOfTokens Total number of tokens */ constructor (uint256 _totalSupplyOfTokens) { _mint(msg.sender, _totalSupplyOfTokens); } /** * @notice Approves and then calls the receiving contract * * @dev call the receiveApproval function on the contract you want to be notified. * receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) */ function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external returns (bool success) { approve(_spender, _value); TokenRecipient(_spender).receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } /** * @dev Interface to use the receiveApproval method */ interface TokenRecipient { /** * @notice Receives a notification of approval of the transfer * @param _from Sender of approval * @param _value The amount of tokens to be spent * @param _tokenContract Address of the token contract * @param _extraData Extra data */ function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes calldata _extraData) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view override 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 override 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 override returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override 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); _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public override returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ abstract contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title Math * @dev Assorted math operations */ 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 Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ 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); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; /** * @notice Base contract for upgradeable contract * @dev Inherited contract should implement verifyState(address) method by checking storage variables * (see verifyState(address) in Dispatcher). Also contract should implement finishUpgrade(address) * if it is using constructor parameters by coping this parameters to the dispatcher storage */ abstract contract Upgradeable is Ownable { event StateVerified(address indexed testTarget, address sender); event UpgradeFinished(address indexed target, address sender); /** * @dev Contracts at the target must reserve the same location in storage for this address as in Dispatcher * Stored data actually lives in the Dispatcher * However the storage layout is specified here in the implementing contracts */ address public target; /** * @dev Previous contract address (if available). Used for rollback */ address public previousTarget; /** * @dev Upgrade status. Explicit `uint8` type is used instead of `bool` to save gas by excluding 0 value */ uint8 public isUpgrade; /** * @dev Guarantees that next slot will be separated from the previous */ uint256 stubSlot; /** * @dev Constants for `isUpgrade` field */ uint8 constant UPGRADE_FALSE = 1; uint8 constant UPGRADE_TRUE = 2; /** * @dev Checks that function executed while upgrading * Recommended to add to `verifyState` and `finishUpgrade` methods */ modifier onlyWhileUpgrading() { require(isUpgrade == UPGRADE_TRUE); _; } /** * @dev Method for verifying storage state. * Should check that new target contract returns right storage value */ function verifyState(address _testTarget) public virtual onlyWhileUpgrading { emit StateVerified(_testTarget, msg.sender); } /** * @dev Copy values from the new target to the current storage * @param _target New target contract address */ function finishUpgrade(address _target) public virtual onlyWhileUpgrading { emit UpgradeFinished(_target, msg.sender); } /** * @dev Base method to get data * @param _target Target to call * @param _selector Method selector * @param _numberOfArguments Number of used arguments * @param _argument1 First method argument * @param _argument2 Second method argument * @return memoryAddress Address in memory where the data is located */ function delegateGetData( address _target, bytes4 _selector, uint8 _numberOfArguments, bytes32 _argument1, bytes32 _argument2 ) internal returns (bytes32 memoryAddress) { assembly { memoryAddress := mload(0x40) mstore(memoryAddress, _selector) if gt(_numberOfArguments, 0) { mstore(add(memoryAddress, 0x04), _argument1) } if gt(_numberOfArguments, 1) { mstore(add(memoryAddress, 0x24), _argument2) } switch delegatecall(gas(), _target, memoryAddress, add(0x04, mul(0x20, _numberOfArguments)), 0, 0) case 0 { revert(memoryAddress, 0) } default { returndatacopy(memoryAddress, 0x0, returndatasize()) } } } /** * @dev Call "getter" without parameters. * Result should not exceed 32 bytes */ function delegateGet(address _target, bytes4 _selector) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 0, 0, 0); assembly { result := mload(memoryAddress) } } /** * @dev Call "getter" with one parameter. * Result should not exceed 32 bytes */ function delegateGet(address _target, bytes4 _selector, bytes32 _argument) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 1, _argument, 0); assembly { result := mload(memoryAddress) } } /** * @dev Call "getter" with two parameters. * Result should not exceed 32 bytes */ function delegateGet( address _target, bytes4 _selector, bytes32 _argument1, bytes32 _argument2 ) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 2, _argument1, _argument2); assembly { result := mload(memoryAddress) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @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 OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public virtual 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; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/math/SafeMath.sol"; /** * @notice Additional math operations */ library AdditionalMath { using SafeMath for uint256; function max16(uint16 a, uint16 b) internal pure returns (uint16) { return a >= b ? a : b; } function min16(uint16 a, uint16 b) internal pure returns (uint16) { return a < b ? a : b; } /** * @notice Division and ceil */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return (a.add(b) - 1) / b; } /** * @dev Adds signed value to unsigned value, throws on overflow. */ function addSigned(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return a.add(uint256(b)); } else { return a.sub(uint256(-b)); } } /** * @dev Subtracts signed value from unsigned value, throws on overflow. */ function subSigned(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return a.sub(uint256(b)); } else { return a.add(uint256(-b)); } } /** * @dev Multiplies two numbers, throws on overflow. */ function mul32(uint32 a, uint32 b) internal pure returns (uint32) { if (a == 0) { return 0; } uint32 c = a * b; assert(c / a == b); return c; } /** * @dev Adds two numbers, throws on overflow. */ function add16(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a + b; assert(c >= a); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub16(uint16 a, uint16 b) internal pure returns (uint16) { assert(b <= a); return a - b; } /** * @dev Adds signed value to unsigned value, throws on overflow. */ function addSigned16(uint16 a, int16 b) internal pure returns (uint16) { if (b >= 0) { return add16(a, uint16(b)); } else { return sub16(a, uint16(-b)); } } /** * @dev Subtracts signed value from unsigned value, throws on overflow. */ function subSigned16(uint16 a, int16 b) internal pure returns (uint16) { if (b >= 0) { return sub16(a, uint16(b)); } else { return add16(a, uint16(-b)); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @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 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value)); } 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(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @dev Taken from https://github.com/ethereum/solidity-examples/blob/master/src/bits/Bits.sol */ library Bits { uint256 internal constant ONE = uint256(1); /** * @notice Sets the bit at the given 'index' in 'self' to: * '1' - if the bit is '0' * '0' - if the bit is '1' * @return The modified value */ function toggleBit(uint256 self, uint8 index) internal pure returns (uint256) { return self ^ ONE << index; } /** * @notice Get the value of the bit at the given 'index' in 'self'. */ function bit(uint256 self, uint8 index) internal pure returns (uint8) { return uint8(self >> index & 1); } /** * @notice Check if the bit at the given 'index' in 'self' is set. * @return 'true' - if the value of the bit is '1', * 'false' - if the value of the bit is '0' */ function bitSet(uint256 self, uint8 index) internal pure returns (bool) { return self >> index & 1 == 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @title Snapshot * @notice Manages snapshots of size 128 bits (32 bits for timestamp, 96 bits for value) * 96 bits is enough for storing NU token values, and 32 bits should be OK for block numbers * @dev Since each storage slot can hold two snapshots, new slots are allocated every other TX. Thus, gas cost of adding snapshots is 51400 and 36400 gas, alternately. * Based on Aragon's Checkpointing (https://https://github.com/aragonone/voting-connectors/blob/master/shared/contract-utils/contracts/Checkpointing.sol) * On average, adding snapshots spends ~6500 less gas than the 256-bit checkpoints of Aragon's Checkpointing */ library Snapshot { function encodeSnapshot(uint32 _time, uint96 _value) internal pure returns(uint128) { return uint128(uint256(_time) << 96 | uint256(_value)); } function decodeSnapshot(uint128 _snapshot) internal pure returns(uint32 time, uint96 value){ time = uint32(bytes4(bytes16(_snapshot))); value = uint96(_snapshot); } function addSnapshot(uint128[] storage _self, uint256 _value) internal { addSnapshot(_self, block.number, _value); } function addSnapshot(uint128[] storage _self, uint256 _time, uint256 _value) internal { uint256 length = _self.length; if (length != 0) { (uint32 currentTime, ) = decodeSnapshot(_self[length - 1]); if (uint32(_time) == currentTime) { _self[length - 1] = encodeSnapshot(uint32(_time), uint96(_value)); return; } else if (uint32(_time) < currentTime){ revert(); } } _self.push(encodeSnapshot(uint32(_time), uint96(_value))); } function lastSnapshot(uint128[] storage _self) internal view returns (uint32, uint96) { uint256 length = _self.length; if (length > 0) { return decodeSnapshot(_self[length - 1]); } return (0, 0); } function lastValue(uint128[] storage _self) internal view returns (uint96) { (, uint96 value) = lastSnapshot(_self); return value; } function getValueAt(uint128[] storage _self, uint256 _time256) internal view returns (uint96) { uint32 _time = uint32(_time256); uint256 length = _self.length; // Short circuit if there's no checkpoints yet // Note that this also lets us avoid using SafeMath later on, as we've established that // there must be at least one checkpoint if (length == 0) { return 0; } // Check last checkpoint uint256 lastIndex = length - 1; (uint32 snapshotTime, uint96 snapshotValue) = decodeSnapshot(_self[length - 1]); if (_time >= snapshotTime) { return snapshotValue; } // Check first checkpoint (if not already checked with the above check on last) (snapshotTime, snapshotValue) = decodeSnapshot(_self[0]); if (length == 1 || _time < snapshotTime) { return 0; } // Do binary search // As we've already checked both ends, we don't need to check the last checkpoint again uint256 low = 0; uint256 high = lastIndex - 1; uint32 midTime; uint96 midValue; while (high > low) { uint256 mid = (high + low + 1) / 2; // average, ceil round (midTime, midValue) = decodeSnapshot(_self[mid]); if (_time > midTime) { low = mid; } else if (_time < midTime) { // Note that we don't need SafeMath here because mid must always be greater than 0 // from the while condition high = mid - 1; } else { // _time == midTime return midValue; } } (, snapshotValue) = decodeSnapshot(_self[low]); return snapshotValue; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; interface IForwarder { function isForwarder() external pure returns (bool); function canForward(address sender, bytes calldata evmCallScript) external view returns (bool); function forward(bytes calldata evmCallScript) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; interface TokenManager { function mint(address _receiver, uint256 _amount) external; function issue(uint256 _amount) external; function assign(address _receiver, uint256 _amount) external; function burn(address _holder, uint256 _amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; import "./IForwarder.sol"; // Interface for Voting contract, as found in https://github.com/aragon/aragon-apps/blob/master/apps/voting/contracts/Voting.sol interface Voting is IForwarder{ enum VoterState { Absent, Yea, Nay } // Public getters function token() external returns (address); function supportRequiredPct() external returns (uint64); function minAcceptQuorumPct() external returns (uint64); function voteTime() external returns (uint64); function votesLength() external returns (uint256); // Setters function changeSupportRequiredPct(uint64 _supportRequiredPct) external; function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external; // Creating new votes function newVote(bytes calldata _executionScript, string memory _metadata) external returns (uint256 voteId); function newVote(bytes calldata _executionScript, string memory _metadata, bool _castVote, bool _executesIfDecided) external returns (uint256 voteId); // Voting function canVote(uint256 _voteId, address _voter) external view returns (bool); function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external; // Executing a passed vote function canExecute(uint256 _voteId) external view returns (bool); function executeVote(uint256 _voteId) external; // Additional info function getVote(uint256 _voteId) external view returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes memory script ); function getVoterState(uint256 _voteId, address _voter) external view returns (VoterState); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/math/SafeMath.sol"; /** * @notice Multi-signature contract with off-chain signing */ contract MultiSig { using SafeMath for uint256; event Executed(address indexed sender, uint256 indexed nonce, address indexed destination, uint256 value); event OwnerAdded(address indexed owner); event OwnerRemoved(address indexed owner); event RequirementChanged(uint16 required); uint256 constant public MAX_OWNER_COUNT = 50; uint256 public nonce; uint8 public required; mapping (address => bool) public isOwner; address[] public owners; /** * @notice Only this contract can call method */ modifier onlyThisContract() { require(msg.sender == address(this)); _; } receive() external payable {} /** * @param _required Number of required signings * @param _owners List of initial owners. */ constructor (uint8 _required, address[] memory _owners) { require(_owners.length <= MAX_OWNER_COUNT && _required <= _owners.length && _required > 0); for (uint256 i = 0; i < _owners.length; i++) { address owner = _owners[i]; require(!isOwner[owner] && owner != address(0)); isOwner[owner] = true; } owners = _owners; required = _required; } /** * @notice Get unsigned hash for transaction parameters * @dev Follows ERC191 signature scheme: https://github.com/ethereum/EIPs/issues/191 * @param _sender Trustee who will execute the transaction * @param _destination Destination address * @param _value Amount of ETH to transfer * @param _data Call data * @param _nonce Nonce */ function getUnsignedTransactionHash( address _sender, address _destination, uint256 _value, bytes memory _data, uint256 _nonce ) public view returns (bytes32) { return keccak256( abi.encodePacked(byte(0x19), byte(0), address(this), _sender, _destination, _value, _data, _nonce)); } /** * @dev Note that address recovered from signatures must be strictly increasing * @param _sigV Array of signatures values V * @param _sigR Array of signatures values R * @param _sigS Array of signatures values S * @param _destination Destination address * @param _value Amount of ETH to transfer * @param _data Call data */ function execute( uint8[] calldata _sigV, bytes32[] calldata _sigR, bytes32[] calldata _sigS, address _destination, uint256 _value, bytes calldata _data ) external { require(_sigR.length >= required && _sigR.length == _sigS.length && _sigR.length == _sigV.length); bytes32 txHash = getUnsignedTransactionHash(msg.sender, _destination, _value, _data, nonce); address lastAdd = address(0); for (uint256 i = 0; i < _sigR.length; i++) { address recovered = ecrecover(txHash, _sigV[i], _sigR[i], _sigS[i]); require(recovered > lastAdd && isOwner[recovered]); lastAdd = recovered; } emit Executed(msg.sender, nonce, _destination, _value); nonce = nonce.add(1); (bool callSuccess,) = _destination.call{value: _value}(_data); require(callSuccess); } /** * @notice Allows to add a new owner * @dev Transaction has to be sent by `execute` method. * @param _owner Address of new owner */ function addOwner(address _owner) external onlyThisContract { require(owners.length < MAX_OWNER_COUNT && _owner != address(0) && !isOwner[_owner]); isOwner[_owner] = true; owners.push(_owner); emit OwnerAdded(_owner); } /** * @notice Allows to remove an owner * @dev Transaction has to be sent by `execute` method. * @param _owner Address of owner */ function removeOwner(address _owner) external onlyThisContract { require(owners.length > required && isOwner[_owner]); isOwner[_owner] = false; for (uint256 i = 0; i < owners.length - 1; i++) { if (owners[i] == _owner) { owners[i] = owners[owners.length - 1]; break; } } owners.pop(); emit OwnerRemoved(_owner); } /** * @notice Returns the number of owners of this MultiSig */ function getNumberOfOwners() external view returns (uint256) { return owners.length; } /** * @notice Allows to change the number of required signatures * @dev Transaction has to be sent by `execute` method * @param _required Number of required signatures */ function changeRequirement(uint8 _required) external onlyThisContract { require(_required <= owners.length && _required > 0); required = _required; emit RequirementChanged(_required); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/token/ERC20/SafeERC20.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/math/Math.sol"; import "../zeppelin/utils/Address.sol"; import "./lib/AdditionalMath.sol"; import "./lib/SignatureVerifier.sol"; import "./StakingEscrow.sol"; import "./NuCypherToken.sol"; import "./proxy/Upgradeable.sol"; /** * @title PolicyManager * @notice Contract holds policy data and locks accrued policy fees * @dev |v6.3.1| */ contract PolicyManager is Upgradeable { using SafeERC20 for NuCypherToken; using SafeMath for uint256; using AdditionalMath for uint256; using AdditionalMath for int256; using AdditionalMath for uint16; using Address for address payable; event PolicyCreated( bytes16 indexed policyId, address indexed sponsor, address indexed owner, uint256 feeRate, uint64 startTimestamp, uint64 endTimestamp, uint256 numberOfNodes ); event ArrangementRevoked( bytes16 indexed policyId, address indexed sender, address indexed node, uint256 value ); event RefundForArrangement( bytes16 indexed policyId, address indexed sender, address indexed node, uint256 value ); event PolicyRevoked(bytes16 indexed policyId, address indexed sender, uint256 value); event RefundForPolicy(bytes16 indexed policyId, address indexed sender, uint256 value); event MinFeeRateSet(address indexed node, uint256 value); // TODO #1501 // Range range event FeeRateRangeSet(address indexed sender, uint256 min, uint256 defaultValue, uint256 max); event Withdrawn(address indexed node, address indexed recipient, uint256 value); struct ArrangementInfo { address node; uint256 indexOfDowntimePeriods; uint16 lastRefundedPeriod; } struct Policy { bool disabled; address payable sponsor; address owner; uint128 feeRate; uint64 startTimestamp; uint64 endTimestamp; uint256 reservedSlot1; uint256 reservedSlot2; uint256 reservedSlot3; uint256 reservedSlot4; uint256 reservedSlot5; ArrangementInfo[] arrangements; } struct NodeInfo { uint128 fee; uint16 previousFeePeriod; uint256 feeRate; uint256 minFeeRate; mapping (uint16 => int256) stub; // former slot for feeDelta mapping (uint16 => int256) feeDelta; } // TODO used only for `delegateGetNodeInfo`, probably will be removed after #1512 struct MemoryNodeInfo { uint128 fee; uint16 previousFeePeriod; uint256 feeRate; uint256 minFeeRate; } struct Range { uint128 min; uint128 defaultValue; uint128 max; } bytes16 internal constant RESERVED_POLICY_ID = bytes16(0); address internal constant RESERVED_NODE = address(0); uint256 internal constant MAX_BALANCE = uint256(uint128(0) - 1); // controlled overflow to get max int256 int256 public constant DEFAULT_FEE_DELTA = int256((uint256(0) - 1) >> 1); StakingEscrow public immutable escrow; uint32 public immutable genesisSecondsPerPeriod; uint32 public immutable secondsPerPeriod; mapping (bytes16 => Policy) public policies; mapping (address => NodeInfo) public nodes; Range public feeRateRange; uint64 public resetTimestamp; /** * @notice Constructor sets address of the escrow contract * @dev Put same address in both inputs variables except when migration is happening * @param _escrowDispatcher Address of escrow dispatcher * @param _escrowImplementation Address of escrow implementation */ constructor(StakingEscrow _escrowDispatcher, StakingEscrow _escrowImplementation) { escrow = _escrowDispatcher; // if the input address is not the StakingEscrow then calling `secondsPerPeriod` will throw error uint32 localSecondsPerPeriod = _escrowImplementation.secondsPerPeriod(); require(localSecondsPerPeriod > 0); secondsPerPeriod = localSecondsPerPeriod; uint32 localgenesisSecondsPerPeriod = _escrowImplementation.genesisSecondsPerPeriod(); require(localgenesisSecondsPerPeriod > 0); genesisSecondsPerPeriod = localgenesisSecondsPerPeriod; // handle case when we deployed new StakingEscrow but not yet upgraded if (_escrowDispatcher != _escrowImplementation) { require(_escrowDispatcher.secondsPerPeriod() == localSecondsPerPeriod || _escrowDispatcher.secondsPerPeriod() == localgenesisSecondsPerPeriod); } } /** * @dev Checks that sender is the StakingEscrow contract */ modifier onlyEscrowContract() { require(msg.sender == address(escrow)); _; } /** * @return Number of current period */ function getCurrentPeriod() public view returns (uint16) { return uint16(block.timestamp / secondsPerPeriod); } /** * @return Recalculate period value using new basis */ function recalculatePeriod(uint16 _period) internal view returns (uint16) { return uint16(uint256(_period) * genesisSecondsPerPeriod / secondsPerPeriod); } /** * @notice Register a node * @param _node Node address * @param _period Initial period */ function register(address _node, uint16 _period) external onlyEscrowContract { NodeInfo storage nodeInfo = nodes[_node]; require(nodeInfo.previousFeePeriod == 0 && _period < getCurrentPeriod()); nodeInfo.previousFeePeriod = _period; } /** * @notice Migrate from the old period length to the new one * @param _node Node address */ function migrate(address _node) external onlyEscrowContract { NodeInfo storage nodeInfo = nodes[_node]; // with previous period length any previousFeePeriod will be greater than current period // this is a sign of not migrated node require(nodeInfo.previousFeePeriod >= getCurrentPeriod()); nodeInfo.previousFeePeriod = recalculatePeriod(nodeInfo.previousFeePeriod); nodeInfo.feeRate = 0; } /** * @notice Set minimum, default & maximum fee rate for all stakers and all policies ('global fee range') */ // TODO # 1501 // function setFeeRateRange(Range calldata _range) external onlyOwner { function setFeeRateRange(uint128 _min, uint128 _default, uint128 _max) external onlyOwner { require(_min <= _default && _default <= _max); feeRateRange = Range(_min, _default, _max); emit FeeRateRangeSet(msg.sender, _min, _default, _max); } /** * @notice Set the minimum acceptable fee rate (set by staker for their associated worker) * @dev Input value must fall within `feeRateRange` (global fee range) */ function setMinFeeRate(uint256 _minFeeRate) external { require(_minFeeRate >= feeRateRange.min && _minFeeRate <= feeRateRange.max, "The staker's min fee rate must fall within the global fee range"); NodeInfo storage nodeInfo = nodes[msg.sender]; if (nodeInfo.minFeeRate == _minFeeRate) { return; } nodeInfo.minFeeRate = _minFeeRate; emit MinFeeRateSet(msg.sender, _minFeeRate); } /** * @notice Get the minimum acceptable fee rate (set by staker for their associated worker) */ function getMinFeeRate(NodeInfo storage _nodeInfo) internal view returns (uint256) { // if minFeeRate has not been set or chosen value falls outside the global fee range // a default value is returned instead if (_nodeInfo.minFeeRate == 0 || _nodeInfo.minFeeRate < feeRateRange.min || _nodeInfo.minFeeRate > feeRateRange.max) { return feeRateRange.defaultValue; } else { return _nodeInfo.minFeeRate; } } /** * @notice Get the minimum acceptable fee rate (set by staker for their associated worker) */ function getMinFeeRate(address _node) public view returns (uint256) { NodeInfo storage nodeInfo = nodes[_node]; return getMinFeeRate(nodeInfo); } /** * @notice Create policy * @dev Generate policy id before creation * @param _policyId Policy id * @param _policyOwner Policy owner. Zero address means sender is owner * @param _endTimestamp End timestamp of the policy in seconds * @param _nodes Nodes that will handle policy */ function createPolicy( bytes16 _policyId, address _policyOwner, uint64 _endTimestamp, address[] calldata _nodes ) external payable { require( _endTimestamp > block.timestamp && msg.value > 0 ); require(address(this).balance <= MAX_BALANCE); uint16 currentPeriod = getCurrentPeriod(); uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1; uint256 numberOfPeriods = endPeriod - currentPeriod; uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods); require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length == msg.value); Policy storage policy = createPolicy(_policyId, _policyOwner, _endTimestamp, feeRate, _nodes.length); for (uint256 i = 0; i < _nodes.length; i++) { address node = _nodes[i]; addFeeToNode(currentPeriod, endPeriod, node, feeRate, int256(feeRate)); policy.arrangements.push(ArrangementInfo(node, 0, 0)); } } /** * @notice Create multiple policies with the same owner, nodes and length * @dev Generate policy ids before creation * @param _policyIds Policy ids * @param _policyOwner Policy owner. Zero address means sender is owner * @param _endTimestamp End timestamp of all policies in seconds * @param _nodes Nodes that will handle all policies */ function createPolicies( bytes16[] calldata _policyIds, address _policyOwner, uint64 _endTimestamp, address[] calldata _nodes ) external payable { require( _endTimestamp > block.timestamp && msg.value > 0 && _policyIds.length > 1 ); require(address(this).balance <= MAX_BALANCE); uint16 currentPeriod = getCurrentPeriod(); uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1; uint256 numberOfPeriods = endPeriod - currentPeriod; uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods / _policyIds.length); require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length * _policyIds.length == msg.value); for (uint256 i = 0; i < _policyIds.length; i++) { Policy storage policy = createPolicy(_policyIds[i], _policyOwner, _endTimestamp, feeRate, _nodes.length); for (uint256 j = 0; j < _nodes.length; j++) { policy.arrangements.push(ArrangementInfo(_nodes[j], 0, 0)); } } int256 fee = int256(_policyIds.length * feeRate); for (uint256 i = 0; i < _nodes.length; i++) { address node = _nodes[i]; addFeeToNode(currentPeriod, endPeriod, node, feeRate, fee); } } /** * @notice Create policy * @param _policyId Policy id * @param _policyOwner Policy owner. Zero address means sender is owner * @param _endTimestamp End timestamp of the policy in seconds * @param _feeRate Fee rate for policy * @param _nodesLength Number of nodes that will handle policy */ function createPolicy( bytes16 _policyId, address _policyOwner, uint64 _endTimestamp, uint128 _feeRate, uint256 _nodesLength ) internal returns (Policy storage policy) { policy = policies[_policyId]; require( _policyId != RESERVED_POLICY_ID && policy.feeRate == 0 && !policy.disabled ); policy.sponsor = msg.sender; policy.startTimestamp = uint64(block.timestamp); policy.endTimestamp = _endTimestamp; policy.feeRate = _feeRate; if (_policyOwner != msg.sender && _policyOwner != address(0)) { policy.owner = _policyOwner; } emit PolicyCreated( _policyId, msg.sender, _policyOwner == address(0) ? msg.sender : _policyOwner, _feeRate, policy.startTimestamp, policy.endTimestamp, _nodesLength ); } /** * @notice Increase fee rate for specified node * @param _currentPeriod Current period * @param _endPeriod End period of policy * @param _node Node that will handle policy * @param _feeRate Fee rate for one policy * @param _overallFeeRate Fee rate for all policies */ function addFeeToNode( uint16 _currentPeriod, uint16 _endPeriod, address _node, uint128 _feeRate, int256 _overallFeeRate ) internal { require(_node != RESERVED_NODE); NodeInfo storage nodeInfo = nodes[_node]; require(nodeInfo.previousFeePeriod != 0 && nodeInfo.previousFeePeriod < _currentPeriod && _feeRate >= getMinFeeRate(nodeInfo)); // Check default value for feeDelta if (nodeInfo.feeDelta[_currentPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[_currentPeriod] = _overallFeeRate; } else { // Overflow protection removed, because ETH total supply less than uint255/int256 nodeInfo.feeDelta[_currentPeriod] += _overallFeeRate; } if (nodeInfo.feeDelta[_endPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[_endPeriod] = -_overallFeeRate; } else { nodeInfo.feeDelta[_endPeriod] -= _overallFeeRate; } // Reset to default value if needed if (nodeInfo.feeDelta[_currentPeriod] == 0) { nodeInfo.feeDelta[_currentPeriod] = DEFAULT_FEE_DELTA; } if (nodeInfo.feeDelta[_endPeriod] == 0) { nodeInfo.feeDelta[_endPeriod] = DEFAULT_FEE_DELTA; } } /** * @notice Get policy owner */ function getPolicyOwner(bytes16 _policyId) public view returns (address) { Policy storage policy = policies[_policyId]; return policy.owner == address(0) ? policy.sponsor : policy.owner; } /** * @notice Call from StakingEscrow to update node info once per period. * Set default `feeDelta` value for specified period and update node fee * @param _node Node address * @param _processedPeriod1 Processed period * @param _processedPeriod2 Processed period * @param _periodToSetDefault Period to set */ function ping( address _node, uint16 _processedPeriod1, uint16 _processedPeriod2, uint16 _periodToSetDefault ) external onlyEscrowContract { NodeInfo storage node = nodes[_node]; // protection from calling not migrated node, see migrate() require(node.previousFeePeriod <= getCurrentPeriod()); if (_processedPeriod1 != 0) { updateFee(node, _processedPeriod1); } if (_processedPeriod2 != 0) { updateFee(node, _processedPeriod2); } // This code increases gas cost for node in trade of decreasing cost for policy sponsor if (_periodToSetDefault != 0 && node.feeDelta[_periodToSetDefault] == 0) { node.feeDelta[_periodToSetDefault] = DEFAULT_FEE_DELTA; } } /** * @notice Update node fee * @param _info Node info structure * @param _period Processed period */ function updateFee(NodeInfo storage _info, uint16 _period) internal { if (_info.previousFeePeriod == 0 || _period <= _info.previousFeePeriod) { return; } for (uint16 i = _info.previousFeePeriod + 1; i <= _period; i++) { int256 delta = _info.feeDelta[i]; if (delta == DEFAULT_FEE_DELTA) { // gas refund _info.feeDelta[i] = 0; continue; } _info.feeRate = _info.feeRate.addSigned(delta); // gas refund _info.feeDelta[i] = 0; } _info.previousFeePeriod = _period; _info.fee += uint128(_info.feeRate); } /** * @notice Withdraw fee by node */ function withdraw() external returns (uint256) { return withdraw(msg.sender); } /** * @notice Withdraw fee by node * @param _recipient Recipient of the fee */ function withdraw(address payable _recipient) public returns (uint256) { NodeInfo storage node = nodes[msg.sender]; uint256 fee = node.fee; require(fee != 0); node.fee = 0; _recipient.sendValue(fee); emit Withdrawn(msg.sender, _recipient, fee); return fee; } /** * @notice Calculate amount of refund * @param _policy Policy * @param _arrangement Arrangement */ function calculateRefundValue(Policy storage _policy, ArrangementInfo storage _arrangement) internal view returns (uint256 refundValue, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod) { uint16 policyStartPeriod = uint16(_policy.startTimestamp / secondsPerPeriod); uint16 maxPeriod = AdditionalMath.min16(getCurrentPeriod(), uint16(_policy.endTimestamp / secondsPerPeriod)); uint16 minPeriod = AdditionalMath.max16(policyStartPeriod, _arrangement.lastRefundedPeriod); uint16 downtimePeriods = 0; uint256 length = escrow.getPastDowntimeLength(_arrangement.node); uint256 initialIndexOfDowntimePeriods; if (_arrangement.lastRefundedPeriod == 0) { initialIndexOfDowntimePeriods = escrow.findIndexOfPastDowntime(_arrangement.node, policyStartPeriod); } else { initialIndexOfDowntimePeriods = _arrangement.indexOfDowntimePeriods; } for (indexOfDowntimePeriods = initialIndexOfDowntimePeriods; indexOfDowntimePeriods < length; indexOfDowntimePeriods++) { (uint16 startPeriod, uint16 endPeriod) = escrow.getPastDowntime(_arrangement.node, indexOfDowntimePeriods); if (startPeriod > maxPeriod) { break; } else if (endPeriod < minPeriod) { continue; } downtimePeriods += AdditionalMath.min16(maxPeriod, endPeriod) .sub16(AdditionalMath.max16(minPeriod, startPeriod)) + 1; if (maxPeriod <= endPeriod) { break; } } uint16 lastCommittedPeriod = escrow.getLastCommittedPeriod(_arrangement.node); if (indexOfDowntimePeriods == length && lastCommittedPeriod < maxPeriod) { // Overflow protection removed: // lastCommittedPeriod < maxPeriod and minPeriod <= maxPeriod + 1 downtimePeriods += maxPeriod - AdditionalMath.max16(minPeriod - 1, lastCommittedPeriod); } refundValue = _policy.feeRate * downtimePeriods; lastRefundedPeriod = maxPeriod + 1; } /** * @notice Revoke/refund arrangement/policy by the sponsor * @param _policyId Policy id * @param _node Node that will be excluded or RESERVED_NODE if full policy should be used ( @param _forceRevoke Force revoke arrangement/policy */ function refundInternal(bytes16 _policyId, address _node, bool _forceRevoke) internal returns (uint256 refundValue) { refundValue = 0; Policy storage policy = policies[_policyId]; require(!policy.disabled && policy.startTimestamp >= resetTimestamp); uint16 endPeriod = uint16(policy.endTimestamp / secondsPerPeriod) + 1; uint256 numberOfActive = policy.arrangements.length; uint256 i = 0; for (; i < policy.arrangements.length; i++) { ArrangementInfo storage arrangement = policy.arrangements[i]; address node = arrangement.node; if (node == RESERVED_NODE || _node != RESERVED_NODE && _node != node) { numberOfActive--; continue; } uint256 nodeRefundValue; (nodeRefundValue, arrangement.indexOfDowntimePeriods, arrangement.lastRefundedPeriod) = calculateRefundValue(policy, arrangement); if (_forceRevoke) { NodeInfo storage nodeInfo = nodes[node]; // Check default value for feeDelta uint16 lastRefundedPeriod = arrangement.lastRefundedPeriod; if (nodeInfo.feeDelta[lastRefundedPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[lastRefundedPeriod] = -int256(policy.feeRate); } else { nodeInfo.feeDelta[lastRefundedPeriod] -= int256(policy.feeRate); } if (nodeInfo.feeDelta[endPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[endPeriod] = int256(policy.feeRate); } else { nodeInfo.feeDelta[endPeriod] += int256(policy.feeRate); } // Reset to default value if needed if (nodeInfo.feeDelta[lastRefundedPeriod] == 0) { nodeInfo.feeDelta[lastRefundedPeriod] = DEFAULT_FEE_DELTA; } if (nodeInfo.feeDelta[endPeriod] == 0) { nodeInfo.feeDelta[endPeriod] = DEFAULT_FEE_DELTA; } nodeRefundValue += uint256(endPeriod - lastRefundedPeriod) * policy.feeRate; } if (_forceRevoke || arrangement.lastRefundedPeriod >= endPeriod) { arrangement.node = RESERVED_NODE; arrangement.indexOfDowntimePeriods = 0; arrangement.lastRefundedPeriod = 0; numberOfActive--; emit ArrangementRevoked(_policyId, msg.sender, node, nodeRefundValue); } else { emit RefundForArrangement(_policyId, msg.sender, node, nodeRefundValue); } refundValue += nodeRefundValue; if (_node != RESERVED_NODE) { break; } } address payable policySponsor = policy.sponsor; if (_node == RESERVED_NODE) { if (numberOfActive == 0) { policy.disabled = true; // gas refund policy.sponsor = address(0); policy.owner = address(0); policy.feeRate = 0; policy.startTimestamp = 0; policy.endTimestamp = 0; emit PolicyRevoked(_policyId, msg.sender, refundValue); } else { emit RefundForPolicy(_policyId, msg.sender, refundValue); } } else { // arrangement not found require(i < policy.arrangements.length); } if (refundValue > 0) { policySponsor.sendValue(refundValue); } } /** * @notice Calculate amount of refund * @param _policyId Policy id * @param _node Node or RESERVED_NODE if all nodes should be used */ function calculateRefundValueInternal(bytes16 _policyId, address _node) internal view returns (uint256 refundValue) { refundValue = 0; Policy storage policy = policies[_policyId]; require((policy.owner == msg.sender || policy.sponsor == msg.sender) && !policy.disabled); uint256 i = 0; for (; i < policy.arrangements.length; i++) { ArrangementInfo storage arrangement = policy.arrangements[i]; if (arrangement.node == RESERVED_NODE || _node != RESERVED_NODE && _node != arrangement.node) { continue; } (uint256 nodeRefundValue,,) = calculateRefundValue(policy, arrangement); refundValue += nodeRefundValue; if (_node != RESERVED_NODE) { break; } } if (_node != RESERVED_NODE) { // arrangement not found require(i < policy.arrangements.length); } } /** * @notice Revoke policy by the sponsor * @param _policyId Policy id */ function revokePolicy(bytes16 _policyId) external returns (uint256 refundValue) { require(getPolicyOwner(_policyId) == msg.sender); return refundInternal(_policyId, RESERVED_NODE, true); } /** * @notice Revoke arrangement by the sponsor * @param _policyId Policy id * @param _node Node that will be excluded */ function revokeArrangement(bytes16 _policyId, address _node) external returns (uint256 refundValue) { require(_node != RESERVED_NODE); require(getPolicyOwner(_policyId) == msg.sender); return refundInternal(_policyId, _node, true); } /** * @notice Get unsigned hash for revocation * @param _policyId Policy id * @param _node Node that will be excluded * @return Revocation hash, EIP191 version 0x45 ('E') */ function getRevocationHash(bytes16 _policyId, address _node) public view returns (bytes32) { return SignatureVerifier.hashEIP191(abi.encodePacked(_policyId, _node), byte(0x45)); } /** * @notice Check correctness of signature * @param _policyId Policy id * @param _node Node that will be excluded, zero address if whole policy will be revoked * @param _signature Signature of owner */ function checkOwnerSignature(bytes16 _policyId, address _node, bytes memory _signature) internal view { bytes32 hash = getRevocationHash(_policyId, _node); address recovered = SignatureVerifier.recover(hash, _signature); require(getPolicyOwner(_policyId) == recovered); } /** * @notice Revoke policy or arrangement using owner's signature * @param _policyId Policy id * @param _node Node that will be excluded, zero address if whole policy will be revoked * @param _signature Signature of owner, EIP191 version 0x45 ('E') */ function revoke(bytes16 _policyId, address _node, bytes calldata _signature) external returns (uint256 refundValue) { checkOwnerSignature(_policyId, _node, _signature); return refundInternal(_policyId, _node, true); } /** * @notice Refund part of fee by the sponsor * @param _policyId Policy id */ function refund(bytes16 _policyId) external { Policy storage policy = policies[_policyId]; require(policy.owner == msg.sender || policy.sponsor == msg.sender); refundInternal(_policyId, RESERVED_NODE, false); } /** * @notice Refund part of one node's fee by the sponsor * @param _policyId Policy id * @param _node Node address */ function refund(bytes16 _policyId, address _node) external returns (uint256 refundValue) { require(_node != RESERVED_NODE); Policy storage policy = policies[_policyId]; require(policy.owner == msg.sender || policy.sponsor == msg.sender); return refundInternal(_policyId, _node, false); } /** * @notice Calculate amount of refund * @param _policyId Policy id */ function calculateRefundValue(bytes16 _policyId) external view returns (uint256 refundValue) { return calculateRefundValueInternal(_policyId, RESERVED_NODE); } /** * @notice Calculate amount of refund * @param _policyId Policy id * @param _node Node */ function calculateRefundValue(bytes16 _policyId, address _node) external view returns (uint256 refundValue) { require(_node != RESERVED_NODE); return calculateRefundValueInternal(_policyId, _node); } /** * @notice Get number of arrangements in the policy * @param _policyId Policy id */ function getArrangementsLength(bytes16 _policyId) external view returns (uint256) { return policies[_policyId].arrangements.length; } /** * @notice Get information about staker's fee rate * @param _node Address of staker * @param _period Period to get fee delta */ function getNodeFeeDelta(address _node, uint16 _period) // TODO "virtual" only for tests, probably will be removed after #1512 public view virtual returns (int256) { // TODO remove after upgrade #2579 if (_node == RESERVED_NODE && _period == 11) { return 55; } return nodes[_node].feeDelta[_period]; } /** * @notice Return the information about arrangement */ function getArrangementInfo(bytes16 _policyId, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (ArrangementInfo) external view returns (address node, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod) { ArrangementInfo storage info = policies[_policyId].arrangements[_index]; node = info.node; indexOfDowntimePeriods = info.indexOfDowntimePeriods; lastRefundedPeriod = info.lastRefundedPeriod; } /** * @dev Get Policy structure by delegatecall */ function delegateGetPolicy(address _target, bytes16 _policyId) internal returns (Policy memory result) { bytes32 memoryAddress = delegateGetData(_target, this.policies.selector, 1, bytes32(_policyId), 0); assembly { result := memoryAddress } } /** * @dev Get ArrangementInfo structure by delegatecall */ function delegateGetArrangementInfo(address _target, bytes16 _policyId, uint256 _index) internal returns (ArrangementInfo memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getArrangementInfo.selector, 2, bytes32(_policyId), bytes32(_index)); assembly { result := memoryAddress } } /** * @dev Get NodeInfo structure by delegatecall */ function delegateGetNodeInfo(address _target, address _node) internal returns (MemoryNodeInfo memory result) { bytes32 memoryAddress = delegateGetData(_target, this.nodes.selector, 1, bytes32(uint256(_node)), 0); assembly { result := memoryAddress } } /** * @dev Get feeRateRange structure by delegatecall */ function delegateGetFeeRateRange(address _target) internal returns (Range memory result) { bytes32 memoryAddress = delegateGetData(_target, this.feeRateRange.selector, 0, 0, 0); assembly { result := memoryAddress } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(uint64(delegateGet(_testTarget, this.resetTimestamp.selector)) == resetTimestamp); Range memory rangeToCheck = delegateGetFeeRateRange(_testTarget); require(feeRateRange.min == rangeToCheck.min && feeRateRange.defaultValue == rangeToCheck.defaultValue && feeRateRange.max == rangeToCheck.max); Policy storage policy = policies[RESERVED_POLICY_ID]; Policy memory policyToCheck = delegateGetPolicy(_testTarget, RESERVED_POLICY_ID); require(policyToCheck.sponsor == policy.sponsor && policyToCheck.owner == policy.owner && policyToCheck.feeRate == policy.feeRate && policyToCheck.startTimestamp == policy.startTimestamp && policyToCheck.endTimestamp == policy.endTimestamp && policyToCheck.disabled == policy.disabled); require(delegateGet(_testTarget, this.getArrangementsLength.selector, RESERVED_POLICY_ID) == policy.arrangements.length); if (policy.arrangements.length > 0) { ArrangementInfo storage arrangement = policy.arrangements[0]; ArrangementInfo memory arrangementToCheck = delegateGetArrangementInfo( _testTarget, RESERVED_POLICY_ID, 0); require(arrangementToCheck.node == arrangement.node && arrangementToCheck.indexOfDowntimePeriods == arrangement.indexOfDowntimePeriods && arrangementToCheck.lastRefundedPeriod == arrangement.lastRefundedPeriod); } NodeInfo storage nodeInfo = nodes[RESERVED_NODE]; MemoryNodeInfo memory nodeInfoToCheck = delegateGetNodeInfo(_testTarget, RESERVED_NODE); require(nodeInfoToCheck.fee == nodeInfo.fee && nodeInfoToCheck.feeRate == nodeInfo.feeRate && nodeInfoToCheck.previousFeePeriod == nodeInfo.previousFeePeriod && nodeInfoToCheck.minFeeRate == nodeInfo.minFeeRate); require(int256(delegateGet(_testTarget, this.getNodeFeeDelta.selector, bytes32(bytes20(RESERVED_NODE)), bytes32(uint256(11)))) == getNodeFeeDelta(RESERVED_NODE, 11)); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); if (resetTimestamp == 0) { resetTimestamp = uint64(block.timestamp); } // Create fake Policy and NodeInfo to use them in verifyState(address) Policy storage policy = policies[RESERVED_POLICY_ID]; policy.sponsor = msg.sender; policy.owner = address(this); policy.startTimestamp = 1; policy.endTimestamp = 2; policy.feeRate = 3; policy.disabled = true; policy.arrangements.push(ArrangementInfo(RESERVED_NODE, 11, 22)); NodeInfo storage nodeInfo = nodes[RESERVED_NODE]; nodeInfo.fee = 100; nodeInfo.feeRate = 33; nodeInfo.previousFeePeriod = 44; nodeInfo.feeDelta[11] = 55; nodeInfo.minFeeRate = 777; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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) { // 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]. * * _Available since v2.4.0._ */ 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"); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./Upgradeable.sol"; import "../../zeppelin/utils/Address.sol"; /** * @notice ERC897 - ERC DelegateProxy */ interface ERCProxy { function proxyType() external pure returns (uint256); function implementation() external view returns (address); } /** * @notice Proxying requests to other contracts. * Client should use ABI of real contract and address of this contract */ contract Dispatcher is Upgradeable, ERCProxy { using Address for address; event Upgraded(address indexed from, address indexed to, address owner); event RolledBack(address indexed from, address indexed to, address owner); /** * @dev Set upgrading status before and after operations */ modifier upgrading() { isUpgrade = UPGRADE_TRUE; _; isUpgrade = UPGRADE_FALSE; } /** * @param _target Target contract address */ constructor(address _target) upgrading { require(_target.isContract()); // Checks that target contract inherits Dispatcher state verifyState(_target); // `verifyState` must work with its contract verifyUpgradeableState(_target, _target); target = _target; finishUpgrade(); emit Upgraded(address(0), _target, msg.sender); } //------------------------ERC897------------------------ /** * @notice ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() external pure override returns (uint256) { return 2; } /** * @notice ERC897, gets the address of the implementation where every call will be delegated */ function implementation() external view override returns (address) { return target; } //------------------------------------------------------------ /** * @notice Verify new contract storage and upgrade target * @param _target New target contract address */ function upgrade(address _target) public onlyOwner upgrading { require(_target.isContract()); // Checks that target contract has "correct" (as much as possible) state layout verifyState(_target); //`verifyState` must work with its contract verifyUpgradeableState(_target, _target); if (target.isContract()) { verifyUpgradeableState(target, _target); } previousTarget = target; target = _target; finishUpgrade(); emit Upgraded(previousTarget, _target, msg.sender); } /** * @notice Rollback to previous target * @dev Test storage carefully before upgrade again after rollback */ function rollback() public onlyOwner upgrading { require(previousTarget.isContract()); emit RolledBack(target, previousTarget, msg.sender); // should be always true because layout previousTarget -> target was already checked // but `verifyState` is not 100% accurate so check again verifyState(previousTarget); if (target.isContract()) { verifyUpgradeableState(previousTarget, target); } target = previousTarget; previousTarget = address(0); finishUpgrade(); } /** * @dev Call verifyState method for Upgradeable contract */ function verifyUpgradeableState(address _from, address _to) private { (bool callSuccess,) = _from.delegatecall(abi.encodeWithSelector(this.verifyState.selector, _to)); require(callSuccess); } /** * @dev Call finishUpgrade method from the Upgradeable contract */ function finishUpgrade() private { (bool callSuccess,) = target.delegatecall(abi.encodeWithSelector(this.finishUpgrade.selector, target)); require(callSuccess); } function verifyState(address _testTarget) public override onlyWhileUpgrading { //checks equivalence accessing state through new contract and current storage require(address(uint160(delegateGet(_testTarget, this.owner.selector))) == owner()); require(address(uint160(delegateGet(_testTarget, this.target.selector))) == target); require(address(uint160(delegateGet(_testTarget, this.previousTarget.selector))) == previousTarget); require(uint8(delegateGet(_testTarget, this.isUpgrade.selector)) == isUpgrade); } /** * @dev Override function using empty code because no reason to call this function in Dispatcher */ function finishUpgrade(address) public override {} /** * @dev Receive function sends empty request to the target contract */ receive() external payable { assert(target.isContract()); // execute receive function from target contract using storage of the dispatcher (bool callSuccess,) = target.delegatecall(""); if (!callSuccess) { revert(); } } /** * @dev Fallback function sends all requests to the target contract */ fallback() external payable { assert(target.isContract()); // execute requested function from target contract using storage of the dispatcher (bool callSuccess,) = target.delegatecall(msg.data); if (callSuccess) { // copy result of the request to the return data // we can use the second return value from `delegatecall` (bytes memory) // but it will consume a little more gas assembly { returndatacopy(0x0, 0x0, returndatasize()) return(0x0, returndatasize()) } } else { revert(); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/utils/Address.sol"; import "../../zeppelin/token/ERC20/SafeERC20.sol"; import "./StakingInterface.sol"; import "../../zeppelin/proxy/Initializable.sol"; /** * @notice Router for accessing interface contract */ contract StakingInterfaceRouter is Ownable { BaseStakingInterface public target; /** * @param _target Address of the interface contract */ constructor(BaseStakingInterface _target) { require(address(_target.token()) != address(0)); target = _target; } /** * @notice Upgrade interface * @param _target New contract address */ function upgrade(BaseStakingInterface _target) external onlyOwner { require(address(_target.token()) != address(0)); target = _target; } } /** * @notice Internal base class for AbstractStakingContract and InitializableStakingContract */ abstract contract RawStakingContract { using Address for address; /** * @dev Returns address of StakingInterfaceRouter */ function router() public view virtual returns (StakingInterfaceRouter); /** * @dev Checks permission for calling fallback function */ function isFallbackAllowed() public virtual returns (bool); /** * @dev Withdraw tokens from staking contract */ function withdrawTokens(uint256 _value) public virtual; /** * @dev Withdraw ETH from staking contract */ function withdrawETH() public virtual; receive() external payable {} /** * @dev Function sends all requests to the target contract */ fallback() external payable { require(isFallbackAllowed()); address target = address(router().target()); require(target.isContract()); // execute requested function from target contract (bool callSuccess, ) = target.delegatecall(msg.data); if (callSuccess) { // copy result of the request to the return data // we can use the second return value from `delegatecall` (bytes memory) // but it will consume a little more gas assembly { returndatacopy(0x0, 0x0, returndatasize()) return(0x0, returndatasize()) } } else { revert(); } } } /** * @notice Base class for any staking contract (not usable with openzeppelin proxy) * @dev Implement `isFallbackAllowed()` or override fallback function * Implement `withdrawTokens(uint256)` and `withdrawETH()` functions */ abstract contract AbstractStakingContract is RawStakingContract { StakingInterfaceRouter immutable router_; NuCypherToken public immutable token; /** * @param _router Interface router contract address */ constructor(StakingInterfaceRouter _router) { router_ = _router; NuCypherToken localToken = _router.target().token(); require(address(localToken) != address(0)); token = localToken; } /** * @dev Returns address of StakingInterfaceRouter */ function router() public view override returns (StakingInterfaceRouter) { return router_; } } /** * @notice Base class for any staking contract usable with openzeppelin proxy * @dev Implement `isFallbackAllowed()` or override fallback function * Implement `withdrawTokens(uint256)` and `withdrawETH()` functions */ abstract contract InitializableStakingContract is Initializable, RawStakingContract { StakingInterfaceRouter router_; NuCypherToken public token; /** * @param _router Interface router contract address */ function initialize(StakingInterfaceRouter _router) public initializer { router_ = _router; NuCypherToken localToken = _router.target().token(); require(address(localToken) != address(0)); token = localToken; } /** * @dev Returns address of StakingInterfaceRouter */ function router() public view override returns (StakingInterfaceRouter) { return router_; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./AbstractStakingContract.sol"; import "../NuCypherToken.sol"; import "../StakingEscrow.sol"; import "../PolicyManager.sol"; import "../WorkLock.sol"; /** * @notice Base StakingInterface */ contract BaseStakingInterface { address public immutable stakingInterfaceAddress; NuCypherToken public immutable token; StakingEscrow public immutable escrow; PolicyManager public immutable policyManager; WorkLock public immutable workLock; /** * @notice Constructor sets addresses of the contracts * @param _token Token contract * @param _escrow Escrow contract * @param _policyManager PolicyManager contract * @param _workLock WorkLock contract */ constructor( NuCypherToken _token, StakingEscrow _escrow, PolicyManager _policyManager, WorkLock _workLock ) { require(_token.totalSupply() > 0 && _escrow.secondsPerPeriod() > 0 && _policyManager.secondsPerPeriod() > 0 && // in case there is no worklock contract (address(_workLock) == address(0) || _workLock.boostingRefund() > 0)); token = _token; escrow = _escrow; policyManager = _policyManager; workLock = _workLock; stakingInterfaceAddress = address(this); } /** * @dev Checks executing through delegate call */ modifier onlyDelegateCall() { require(stakingInterfaceAddress != address(this)); _; } /** * @dev Checks the existence of the worklock contract */ modifier workLockSet() { require(address(workLock) != address(0)); _; } } /** * @notice Interface for accessing main contracts from a staking contract * @dev All methods must be stateless because this code will be executed by delegatecall call, use immutable fields. * @dev |v1.7.1| */ contract StakingInterface is BaseStakingInterface { event DepositedAsStaker(address indexed sender, uint256 value, uint16 periods); event WithdrawnAsStaker(address indexed sender, uint256 value); event DepositedAndIncreased(address indexed sender, uint256 index, uint256 value); event LockedAndCreated(address indexed sender, uint256 value, uint16 periods); event LockedAndIncreased(address indexed sender, uint256 index, uint256 value); event Divided(address indexed sender, uint256 index, uint256 newValue, uint16 periods); event Merged(address indexed sender, uint256 index1, uint256 index2); event Minted(address indexed sender); event PolicyFeeWithdrawn(address indexed sender, uint256 value); event MinFeeRateSet(address indexed sender, uint256 value); event ReStakeSet(address indexed sender, bool reStake); event WorkerBonded(address indexed sender, address worker); event Prolonged(address indexed sender, uint256 index, uint16 periods); event WindDownSet(address indexed sender, bool windDown); event SnapshotSet(address indexed sender, bool snapshotsEnabled); event Bid(address indexed sender, uint256 depositedETH); event Claimed(address indexed sender, uint256 claimedTokens); event Refund(address indexed sender, uint256 refundETH); event BidCanceled(address indexed sender); event CompensationWithdrawn(address indexed sender); /** * @notice Constructor sets addresses of the contracts * @param _token Token contract * @param _escrow Escrow contract * @param _policyManager PolicyManager contract * @param _workLock WorkLock contract */ constructor( NuCypherToken _token, StakingEscrow _escrow, PolicyManager _policyManager, WorkLock _workLock ) BaseStakingInterface(_token, _escrow, _policyManager, _workLock) { } /** * @notice Bond worker in the staking escrow * @param _worker Worker address */ function bondWorker(address _worker) public onlyDelegateCall { escrow.bondWorker(_worker); emit WorkerBonded(msg.sender, _worker); } /** * @notice Set `reStake` parameter in the staking escrow * @param _reStake Value for parameter */ function setReStake(bool _reStake) public onlyDelegateCall { escrow.setReStake(_reStake); emit ReStakeSet(msg.sender, _reStake); } /** * @notice Deposit tokens to the staking escrow * @param _value Amount of token to deposit * @param _periods Amount of periods during which tokens will be locked */ function depositAsStaker(uint256 _value, uint16 _periods) public onlyDelegateCall { require(token.balanceOf(address(this)) >= _value); token.approve(address(escrow), _value); escrow.deposit(address(this), _value, _periods); emit DepositedAsStaker(msg.sender, _value, _periods); } /** * @notice Deposit tokens to the staking escrow * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function depositAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall { require(token.balanceOf(address(this)) >= _value); token.approve(address(escrow), _value); escrow.depositAndIncrease(_index, _value); emit DepositedAndIncreased(msg.sender, _index, _value); } /** * @notice Withdraw available amount of tokens from the staking escrow to the staking contract * @param _value Amount of token to withdraw */ function withdrawAsStaker(uint256 _value) public onlyDelegateCall { escrow.withdraw(_value); emit WithdrawnAsStaker(msg.sender, _value); } /** * @notice Lock some tokens in the staking escrow * @param _value Amount of tokens which should lock * @param _periods Amount of periods during which tokens will be locked */ function lockAndCreate(uint256 _value, uint16 _periods) public onlyDelegateCall { escrow.lockAndCreate(_value, _periods); emit LockedAndCreated(msg.sender, _value, _periods); } /** * @notice Lock some tokens in the staking escrow * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall { escrow.lockAndIncrease(_index, _value); emit LockedAndIncreased(msg.sender, _index, _value); } /** * @notice Divide stake into two parts * @param _index Index of stake * @param _newValue New stake value * @param _periods Amount of periods for extending stake */ function divideStake(uint256 _index, uint256 _newValue, uint16 _periods) public onlyDelegateCall { escrow.divideStake(_index, _newValue, _periods); emit Divided(msg.sender, _index, _newValue, _periods); } /** * @notice Merge two sub-stakes into one * @param _index1 Index of the first sub-stake * @param _index2 Index of the second sub-stake */ function mergeStake(uint256 _index1, uint256 _index2) public onlyDelegateCall { escrow.mergeStake(_index1, _index2); emit Merged(msg.sender, _index1, _index2); } /** * @notice Mint tokens in the staking escrow */ function mint() public onlyDelegateCall { escrow.mint(); emit Minted(msg.sender); } /** * @notice Withdraw available policy fees from the policy manager to the staking contract */ function withdrawPolicyFee() public onlyDelegateCall { uint256 value = policyManager.withdraw(); emit PolicyFeeWithdrawn(msg.sender, value); } /** * @notice Set the minimum fee that the staker will accept in the policy manager contract */ function setMinFeeRate(uint256 _minFeeRate) public onlyDelegateCall { policyManager.setMinFeeRate(_minFeeRate); emit MinFeeRateSet(msg.sender, _minFeeRate); } /** * @notice Prolong active sub stake * @param _index Index of the sub stake * @param _periods Amount of periods for extending sub stake */ function prolongStake(uint256 _index, uint16 _periods) public onlyDelegateCall { escrow.prolongStake(_index, _periods); emit Prolonged(msg.sender, _index, _periods); } /** * @notice Set `windDown` parameter in the staking escrow * @param _windDown Value for parameter */ function setWindDown(bool _windDown) public onlyDelegateCall { escrow.setWindDown(_windDown); emit WindDownSet(msg.sender, _windDown); } /** * @notice Set `snapshots` parameter in the staking escrow * @param _enableSnapshots Value for parameter */ function setSnapshots(bool _enableSnapshots) public onlyDelegateCall { escrow.setSnapshots(_enableSnapshots); emit SnapshotSet(msg.sender, _enableSnapshots); } /** * @notice Bid for tokens by transferring ETH */ function bid(uint256 _value) public payable onlyDelegateCall workLockSet { workLock.bid{value: _value}(); emit Bid(msg.sender, _value); } /** * @notice Cancel bid and refund deposited ETH */ function cancelBid() public onlyDelegateCall workLockSet { workLock.cancelBid(); emit BidCanceled(msg.sender); } /** * @notice Withdraw compensation after force refund */ function withdrawCompensation() public onlyDelegateCall workLockSet { workLock.withdrawCompensation(); emit CompensationWithdrawn(msg.sender); } /** * @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract */ function claim() public onlyDelegateCall workLockSet { uint256 claimedTokens = workLock.claim(); emit Claimed(msg.sender, claimedTokens); } /** * @notice Refund ETH for the completed work */ function refund() public onlyDelegateCall workLockSet { uint256 refundETH = workLock.refund(); emit Refund(msg.sender, refundETH); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/token/ERC20/SafeERC20.sol"; import "../zeppelin/utils/Address.sol"; import "../zeppelin/ownership/Ownable.sol"; import "./NuCypherToken.sol"; import "./StakingEscrow.sol"; import "./lib/AdditionalMath.sol"; /** * @notice The WorkLock distribution contract */ contract WorkLock is Ownable { using SafeERC20 for NuCypherToken; using SafeMath for uint256; using AdditionalMath for uint256; using Address for address payable; using Address for address; event Deposited(address indexed sender, uint256 value); event Bid(address indexed sender, uint256 depositedETH); event Claimed(address indexed sender, uint256 claimedTokens); event Refund(address indexed sender, uint256 refundETH, uint256 completedWork); event Canceled(address indexed sender, uint256 value); event BiddersChecked(address indexed sender, uint256 startIndex, uint256 endIndex); event ForceRefund(address indexed sender, address indexed bidder, uint256 refundETH); event CompensationWithdrawn(address indexed sender, uint256 value); event Shutdown(address indexed sender); struct WorkInfo { uint256 depositedETH; uint256 completedWork; bool claimed; uint128 index; } uint16 public constant SLOWING_REFUND = 100; uint256 private constant MAX_ETH_SUPPLY = 2e10 ether; NuCypherToken public immutable token; StakingEscrow public immutable escrow; /* * @dev WorkLock calculations: * bid = minBid + bonusETHPart * bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens * bonusDepositRate = bonusTokenSupply / bonusETHSupply * claimedTokens = minAllowableLockedTokens + bonusETHPart * bonusDepositRate * bonusRefundRate = bonusDepositRate * SLOWING_REFUND / boostingRefund * refundETH = completedWork / refundRate */ uint256 public immutable boostingRefund; uint256 public immutable minAllowedBid; uint16 public immutable stakingPeriods; // copy from the escrow contract uint256 public immutable maxAllowableLockedTokens; uint256 public immutable minAllowableLockedTokens; uint256 public tokenSupply; uint256 public startBidDate; uint256 public endBidDate; uint256 public endCancellationDate; uint256 public bonusETHSupply; mapping(address => WorkInfo) public workInfo; mapping(address => uint256) public compensation; address[] public bidders; // if value == bidders.length then WorkLock is fully checked uint256 public nextBidderToCheck; /** * @dev Checks timestamp regarding cancellation window */ modifier afterCancellationWindow() { require(block.timestamp >= endCancellationDate, "Operation is allowed when cancellation phase is over"); _; } /** * @param _token Token contract * @param _escrow Escrow contract * @param _startBidDate Timestamp when bidding starts * @param _endBidDate Timestamp when bidding will end * @param _endCancellationDate Timestamp when cancellation will ends * @param _boostingRefund Coefficient to boost refund ETH * @param _stakingPeriods Amount of periods during which tokens will be locked after claiming * @param _minAllowedBid Minimum allowed ETH amount for bidding */ constructor( NuCypherToken _token, StakingEscrow _escrow, uint256 _startBidDate, uint256 _endBidDate, uint256 _endCancellationDate, uint256 _boostingRefund, uint16 _stakingPeriods, uint256 _minAllowedBid ) { uint256 totalSupply = _token.totalSupply(); require(totalSupply > 0 && // token contract is deployed and accessible _escrow.secondsPerPeriod() > 0 && // escrow contract is deployed and accessible _escrow.token() == _token && // same token address for worklock and escrow _endBidDate > _startBidDate && // bidding period lasts some time _endBidDate > block.timestamp && // there is time to make a bid _endCancellationDate >= _endBidDate && // cancellation window includes bidding _minAllowedBid > 0 && // min allowed bid was set _boostingRefund > 0 && // boosting coefficient was set _stakingPeriods >= _escrow.minLockedPeriods()); // staking duration is consistent with escrow contract // worst case for `ethToWork()` and `workToETH()`, // when ethSupply == MAX_ETH_SUPPLY and tokenSupply == totalSupply require(MAX_ETH_SUPPLY * totalSupply * SLOWING_REFUND / MAX_ETH_SUPPLY / totalSupply == SLOWING_REFUND && MAX_ETH_SUPPLY * totalSupply * _boostingRefund / MAX_ETH_SUPPLY / totalSupply == _boostingRefund); token = _token; escrow = _escrow; startBidDate = _startBidDate; endBidDate = _endBidDate; endCancellationDate = _endCancellationDate; boostingRefund = _boostingRefund; stakingPeriods = _stakingPeriods; minAllowedBid = _minAllowedBid; maxAllowableLockedTokens = _escrow.maxAllowableLockedTokens(); minAllowableLockedTokens = _escrow.minAllowableLockedTokens(); } /** * @notice Deposit tokens to contract * @param _value Amount of tokens to transfer */ function tokenDeposit(uint256 _value) external { require(block.timestamp < endBidDate, "Can't deposit more tokens after end of bidding"); token.safeTransferFrom(msg.sender, address(this), _value); tokenSupply += _value; emit Deposited(msg.sender, _value); } /** * @notice Calculate amount of tokens that will be get for specified amount of ETH * @dev This value will be fixed only after end of bidding */ function ethToTokens(uint256 _ethAmount) public view returns (uint256) { if (_ethAmount < minAllowedBid) { return 0; } // when all participants bid with the same minimum amount of eth if (bonusETHSupply == 0) { return tokenSupply / bidders.length; } uint256 bonusETH = _ethAmount - minAllowedBid; uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens; return minAllowableLockedTokens + bonusETH.mul(bonusTokenSupply).div(bonusETHSupply); } /** * @notice Calculate amount of work that need to be done to refund specified amount of ETH */ function ethToWork(uint256 _ethAmount, uint256 _tokenSupply, uint256 _ethSupply) internal view returns (uint256) { return _ethAmount.mul(_tokenSupply).mul(SLOWING_REFUND).divCeil(_ethSupply.mul(boostingRefund)); } /** * @notice Calculate amount of work that need to be done to refund specified amount of ETH * @dev This value will be fixed only after end of bidding * @param _ethToReclaim Specified sum of ETH staker wishes to reclaim following completion of work * @param _restOfDepositedETH Remaining ETH in staker's deposit once ethToReclaim sum has been subtracted * @dev _ethToReclaim + _restOfDepositedETH = depositedETH */ function ethToWork(uint256 _ethToReclaim, uint256 _restOfDepositedETH) internal view returns (uint256) { uint256 baseETHSupply = bidders.length * minAllowedBid; // when all participants bid with the same minimum amount of eth if (bonusETHSupply == 0) { return ethToWork(_ethToReclaim, tokenSupply, baseETHSupply); } uint256 baseETH = 0; uint256 bonusETH = 0; // If the staker's total remaining deposit (including the specified sum of ETH to reclaim) // is lower than the minimum bid size, // then only the base part is used to calculate the work required to reclaim ETH if (_ethToReclaim + _restOfDepositedETH <= minAllowedBid) { baseETH = _ethToReclaim; // If the staker's remaining deposit (not including the specified sum of ETH to reclaim) // is still greater than the minimum bid size, // then only the bonus part is used to calculate the work required to reclaim ETH } else if (_restOfDepositedETH >= minAllowedBid) { bonusETH = _ethToReclaim; // If the staker's remaining deposit (not including the specified sum of ETH to reclaim) // is lower than the minimum bid size, // then both the base and bonus parts must be used to calculate the work required to reclaim ETH } else { bonusETH = _ethToReclaim + _restOfDepositedETH - minAllowedBid; baseETH = _ethToReclaim - bonusETH; } uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens; uint256 work = 0; if (baseETH > 0) { work = ethToWork(baseETH, baseTokenSupply, baseETHSupply); } if (bonusETH > 0) { uint256 bonusTokenSupply = tokenSupply - baseTokenSupply; work += ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply); } return work; } /** * @notice Calculate amount of work that need to be done to refund specified amount of ETH * @dev This value will be fixed only after end of bidding */ function ethToWork(uint256 _ethAmount) public view returns (uint256) { return ethToWork(_ethAmount, 0); } /** * @notice Calculate amount of ETH that will be refund for completing specified amount of work */ function workToETH(uint256 _completedWork, uint256 _ethSupply, uint256 _tokenSupply) internal view returns (uint256) { return _completedWork.mul(_ethSupply).mul(boostingRefund).div(_tokenSupply.mul(SLOWING_REFUND)); } /** * @notice Calculate amount of ETH that will be refund for completing specified amount of work * @dev This value will be fixed only after end of bidding */ function workToETH(uint256 _completedWork, uint256 _depositedETH) public view returns (uint256) { uint256 baseETHSupply = bidders.length * minAllowedBid; // when all participants bid with the same minimum amount of eth if (bonusETHSupply == 0) { return workToETH(_completedWork, baseETHSupply, tokenSupply); } uint256 bonusWork = 0; uint256 bonusETH = 0; uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens; if (_depositedETH > minAllowedBid) { bonusETH = _depositedETH - minAllowedBid; uint256 bonusTokenSupply = tokenSupply - baseTokenSupply; bonusWork = ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply); if (_completedWork <= bonusWork) { return workToETH(_completedWork, bonusETHSupply, bonusTokenSupply); } } _completedWork -= bonusWork; return bonusETH + workToETH(_completedWork, baseETHSupply, baseTokenSupply); } /** * @notice Get remaining work to full refund */ function getRemainingWork(address _bidder) external view returns (uint256) { WorkInfo storage info = workInfo[_bidder]; uint256 completedWork = escrow.getCompletedWork(_bidder).sub(info.completedWork); uint256 remainingWork = ethToWork(info.depositedETH); if (remainingWork <= completedWork) { return 0; } return remainingWork - completedWork; } /** * @notice Get length of bidders array */ function getBiddersLength() external view returns (uint256) { return bidders.length; } /** * @notice Bid for tokens by transferring ETH */ function bid() external payable { require(block.timestamp >= startBidDate, "Bidding is not open yet"); require(block.timestamp < endBidDate, "Bidding is already finished"); WorkInfo storage info = workInfo[msg.sender]; // first bid if (info.depositedETH == 0) { require(msg.value >= minAllowedBid, "Bid must be at least minimum"); require(bidders.length < tokenSupply / minAllowableLockedTokens, "Not enough tokens for more bidders"); info.index = uint128(bidders.length); bidders.push(msg.sender); bonusETHSupply = bonusETHSupply.add(msg.value - minAllowedBid); } else { bonusETHSupply = bonusETHSupply.add(msg.value); } info.depositedETH = info.depositedETH.add(msg.value); emit Bid(msg.sender, msg.value); } /** * @notice Cancel bid and refund deposited ETH */ function cancelBid() external { require(block.timestamp < endCancellationDate, "Cancellation allowed only during cancellation window"); WorkInfo storage info = workInfo[msg.sender]; require(info.depositedETH > 0, "No bid to cancel"); require(!info.claimed, "Tokens are already claimed"); uint256 refundETH = info.depositedETH; info.depositedETH = 0; // remove from bidders array, move last bidder to the empty place uint256 lastIndex = bidders.length - 1; if (info.index != lastIndex) { address lastBidder = bidders[lastIndex]; bidders[info.index] = lastBidder; workInfo[lastBidder].index = info.index; } bidders.pop(); if (refundETH > minAllowedBid) { bonusETHSupply = bonusETHSupply.sub(refundETH - minAllowedBid); } msg.sender.sendValue(refundETH); emit Canceled(msg.sender, refundETH); } /** * @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens */ function shutdown() external onlyOwner { require(!isClaimingAvailable(), "Claiming has already been enabled"); internalShutdown(); } /** * @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens */ function internalShutdown() internal { startBidDate = 0; endBidDate = 0; endCancellationDate = uint256(0) - 1; // "infinite" cancellation window token.safeTransfer(owner(), tokenSupply); emit Shutdown(msg.sender); } /** * @notice Make force refund to bidders who can get tokens more than maximum allowed * @param _biddersForRefund Sorted list of unique bidders. Only bidders who must receive a refund */ function forceRefund(address payable[] calldata _biddersForRefund) external afterCancellationWindow { require(nextBidderToCheck != bidders.length, "Bidders have already been checked"); uint256 length = _biddersForRefund.length; require(length > 0, "Must be at least one bidder for a refund"); uint256 minNumberOfBidders = tokenSupply.divCeil(maxAllowableLockedTokens); if (bidders.length < minNumberOfBidders) { internalShutdown(); return; } address previousBidder = _biddersForRefund[0]; uint256 minBid = workInfo[previousBidder].depositedETH; uint256 maxBid = minBid; // get minimum and maximum bids for (uint256 i = 1; i < length; i++) { address bidder = _biddersForRefund[i]; uint256 depositedETH = workInfo[bidder].depositedETH; require(bidder > previousBidder && depositedETH > 0, "Addresses must be an array of unique bidders"); if (minBid > depositedETH) { minBid = depositedETH; } else if (maxBid < depositedETH) { maxBid = depositedETH; } previousBidder = bidder; } uint256[] memory refunds = new uint256[](length); // first step - align at a minimum bid if (minBid != maxBid) { for (uint256 i = 0; i < length; i++) { address bidder = _biddersForRefund[i]; WorkInfo storage info = workInfo[bidder]; if (info.depositedETH > minBid) { refunds[i] = info.depositedETH - minBid; info.depositedETH = minBid; bonusETHSupply -= refunds[i]; } } } require(ethToTokens(minBid) > maxAllowableLockedTokens, "At least one of bidders has allowable bid"); // final bids adjustment (only for bonus part) // (min_whale_bid * token_supply - max_stake * eth_supply) / (token_supply - max_stake * n_whales) uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens; uint256 minBonusETH = minBid - minAllowedBid; uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens; uint256 refundETH = minBonusETH.mul(bonusTokenSupply) .sub(maxBonusTokens.mul(bonusETHSupply)) .divCeil(bonusTokenSupply - maxBonusTokens.mul(length)); uint256 resultBid = minBid.sub(refundETH); bonusETHSupply -= length * refundETH; for (uint256 i = 0; i < length; i++) { address bidder = _biddersForRefund[i]; WorkInfo storage info = workInfo[bidder]; refunds[i] += refundETH; info.depositedETH = resultBid; } // reset verification nextBidderToCheck = 0; // save a refund for (uint256 i = 0; i < length; i++) { address bidder = _biddersForRefund[i]; compensation[bidder] += refunds[i]; emit ForceRefund(msg.sender, bidder, refunds[i]); } } /** * @notice Withdraw compensation after force refund */ function withdrawCompensation() external { uint256 refund = compensation[msg.sender]; require(refund > 0, "There is no compensation"); compensation[msg.sender] = 0; msg.sender.sendValue(refund); emit CompensationWithdrawn(msg.sender, refund); } /** * @notice Check that the claimed tokens are within `maxAllowableLockedTokens` for all participants, * starting from the last point `nextBidderToCheck` * @dev Method stops working when the remaining gas is less than `_gasToSaveState` * and saves the state in `nextBidderToCheck`. * If all bidders have been checked then `nextBidderToCheck` will be equal to the length of the bidders array */ function verifyBiddingCorrectness(uint256 _gasToSaveState) external afterCancellationWindow returns (uint256) { require(nextBidderToCheck != bidders.length, "Bidders have already been checked"); // all participants bid with the same minimum amount of eth uint256 index = nextBidderToCheck; if (bonusETHSupply == 0) { require(tokenSupply / bidders.length <= maxAllowableLockedTokens, "Not enough bidders"); index = bidders.length; } uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens; uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens; uint256 maxBidFromMaxStake = minAllowedBid + maxBonusTokens.mul(bonusETHSupply).div(bonusTokenSupply); while (index < bidders.length && gasleft() > _gasToSaveState) { address bidder = bidders[index]; require(workInfo[bidder].depositedETH <= maxBidFromMaxStake, "Bid is greater than max allowable bid"); index++; } if (index != nextBidderToCheck) { emit BiddersChecked(msg.sender, nextBidderToCheck, index); nextBidderToCheck = index; } return nextBidderToCheck; } /** * @notice Checks if claiming available */ function isClaimingAvailable() public view returns (bool) { return block.timestamp >= endCancellationDate && nextBidderToCheck == bidders.length; } /** * @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract. */ function claim() external returns (uint256 claimedTokens) { require(isClaimingAvailable(), "Claiming has not been enabled yet"); WorkInfo storage info = workInfo[msg.sender]; require(!info.claimed, "Tokens are already claimed"); claimedTokens = ethToTokens(info.depositedETH); require(claimedTokens > 0, "Nothing to claim"); info.claimed = true; token.approve(address(escrow), claimedTokens); escrow.depositFromWorkLock(msg.sender, claimedTokens, stakingPeriods); info.completedWork = escrow.setWorkMeasurement(msg.sender, true); emit Claimed(msg.sender, claimedTokens); } /** * @notice Get available refund for bidder */ function getAvailableRefund(address _bidder) public view returns (uint256) { WorkInfo storage info = workInfo[_bidder]; // nothing to refund if (info.depositedETH == 0) { return 0; } uint256 currentWork = escrow.getCompletedWork(_bidder); uint256 completedWork = currentWork.sub(info.completedWork); // no work that has been completed since last refund if (completedWork == 0) { return 0; } uint256 refundETH = workToETH(completedWork, info.depositedETH); if (refundETH > info.depositedETH) { refundETH = info.depositedETH; } return refundETH; } /** * @notice Refund ETH for the completed work */ function refund() external returns (uint256 refundETH) { WorkInfo storage info = workInfo[msg.sender]; require(info.claimed, "Tokens must be claimed before refund"); refundETH = getAvailableRefund(msg.sender); require(refundETH > 0, "Nothing to refund: there is no ETH to refund or no completed work"); if (refundETH == info.depositedETH) { escrow.setWorkMeasurement(msg.sender, false); } info.depositedETH = info.depositedETH.sub(refundETH); // convert refund back to work to eliminate potential rounding errors uint256 completedWork = ethToWork(refundETH, info.depositedETH); info.completedWork = info.completedWork.add(completedWork); emit Refund(msg.sender, refundETH, completedWork); msg.sender.sendValue(refundETH); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract acts as delegate for sub-stakers and owner **/ contract PoolingStakingContract is AbstractStakingContract, Ownable { using SafeMath for uint256; using Address for address payable; using SafeERC20 for NuCypherToken; event TokensDeposited(address indexed sender, uint256 value, uint256 depositedTokens); event TokensWithdrawn(address indexed sender, uint256 value, uint256 depositedTokens); event ETHWithdrawn(address indexed sender, uint256 value); event DepositSet(address indexed sender, bool value); struct Delegator { uint256 depositedTokens; uint256 withdrawnReward; uint256 withdrawnETH; } StakingEscrow public immutable escrow; uint256 public totalDepositedTokens; uint256 public totalWithdrawnReward; uint256 public totalWithdrawnETH; uint256 public ownerFraction; uint256 public ownerWithdrawnReward; uint256 public ownerWithdrawnETH; mapping (address => Delegator) public delegators; bool depositIsEnabled = true; /** * @param _router Address of the StakingInterfaceRouter contract * @param _ownerFraction Base owner's portion of reward */ constructor( StakingInterfaceRouter _router, uint256 _ownerFraction ) AbstractStakingContract(_router) { escrow = _router.target().escrow(); ownerFraction = _ownerFraction; } /** * @notice Enabled deposit */ function enableDeposit() external onlyOwner { depositIsEnabled = true; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Disable deposit */ function disableDeposit() external onlyOwner { depositIsEnabled = false; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Transfer tokens as delegator * @param _value Amount of tokens to transfer */ function depositTokens(uint256 _value) external { require(depositIsEnabled, "Deposit must be enabled"); require(_value > 0, "Value must be not empty"); totalDepositedTokens = totalDepositedTokens.add(_value); Delegator storage delegator = delegators[msg.sender]; delegator.depositedTokens += _value; token.safeTransferFrom(msg.sender, address(this), _value); emit TokensDeposited(msg.sender, _value, delegator.depositedTokens); } /** * @notice Get available reward for all delegators and owner */ function getAvailableReward() public view returns (uint256) { uint256 stakedTokens = escrow.getAllTokens(address(this)); uint256 freeTokens = token.balanceOf(address(this)); uint256 reward = stakedTokens + freeTokens - totalDepositedTokens; if (reward > freeTokens) { return freeTokens; } return reward; } /** * @notice Get cumulative reward */ function getCumulativeReward() public view returns (uint256) { return getAvailableReward().add(totalWithdrawnReward); } /** * @notice Get available reward in tokens for pool owner */ function getAvailableOwnerReward() public view returns (uint256) { uint256 reward = getCumulativeReward(); uint256 maxAllowableReward; if (totalDepositedTokens != 0) { maxAllowableReward = reward.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction)); } else { maxAllowableReward = reward; } return maxAllowableReward.sub(ownerWithdrawnReward); } /** * @notice Get available reward in tokens for delegator */ function getAvailableReward(address _delegator) public view returns (uint256) { if (totalDepositedTokens == 0) { return 0; } uint256 reward = getCumulativeReward(); Delegator storage delegator = delegators[_delegator]; uint256 maxAllowableReward = reward.mul(delegator.depositedTokens) .div(totalDepositedTokens.add(ownerFraction)); return maxAllowableReward > delegator.withdrawnReward ? maxAllowableReward - delegator.withdrawnReward : 0; } /** * @notice Withdraw reward in tokens to owner */ function withdrawOwnerReward() public onlyOwner { uint256 balance = token.balanceOf(address(this)); uint256 availableReward = getAvailableOwnerReward(); if (availableReward > balance) { availableReward = balance; } require(availableReward > 0, "There is no available reward to withdraw"); ownerWithdrawnReward = ownerWithdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); token.safeTransfer(msg.sender, availableReward); emit TokensWithdrawn(msg.sender, availableReward, 0); } /** * @notice Withdraw amount of tokens to delegator * @param _value Amount of tokens to withdraw */ function withdrawTokens(uint256 _value) public override { uint256 balance = token.balanceOf(address(this)); require(_value <= balance, "Not enough tokens in the contract"); uint256 availableReward = getAvailableReward(msg.sender); Delegator storage delegator = delegators[msg.sender]; require(_value <= availableReward + delegator.depositedTokens, "Requested amount of tokens exceeded allowed portion"); if (_value <= availableReward) { delegator.withdrawnReward += _value; totalWithdrawnReward += _value; } else { delegator.withdrawnReward = delegator.withdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); uint256 depositToWithdraw = _value - availableReward; uint256 newDepositedTokens = delegator.depositedTokens - depositToWithdraw; uint256 newWithdrawnReward = delegator.withdrawnReward.mul(newDepositedTokens).div(delegator.depositedTokens); uint256 newWithdrawnETH = delegator.withdrawnETH.mul(newDepositedTokens).div(delegator.depositedTokens); totalDepositedTokens -= depositToWithdraw; totalWithdrawnReward -= (delegator.withdrawnReward - newWithdrawnReward); totalWithdrawnETH -= (delegator.withdrawnETH - newWithdrawnETH); delegator.depositedTokens = newDepositedTokens; delegator.withdrawnReward = newWithdrawnReward; delegator.withdrawnETH = newWithdrawnETH; } token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens); } /** * @notice Get available ether for owner */ function getAvailableOwnerETH() public view returns (uint256) { // TODO boilerplate code uint256 balance = address(this).balance; balance = balance.add(totalWithdrawnETH); uint256 maxAllowableETH = balance.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction)); uint256 availableETH = maxAllowableETH.sub(ownerWithdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Get available ether for delegator */ function getAvailableETH(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; // TODO boilerplate code uint256 balance = address(this).balance; balance = balance.add(totalWithdrawnETH); uint256 maxAllowableETH = balance.mul(delegator.depositedTokens) .div(totalDepositedTokens.add(ownerFraction)); uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Withdraw available amount of ETH to pool owner */ function withdrawOwnerETH() public onlyOwner { uint256 availableETH = getAvailableOwnerETH(); require(availableETH > 0, "There is no available ETH to withdraw"); ownerWithdrawnETH = ownerWithdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } /** * @notice Withdraw available amount of ETH to delegator */ function withdrawETH() public override { uint256 availableETH = getAvailableETH(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); Delegator storage delegator = delegators[msg.sender]; delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } /** * @notice Calling fallback function is allowed only for the owner **/ function isFallbackAllowed() public view override returns (bool) { return msg.sender == owner(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract acts as delegate for sub-stakers **/ contract PoolingStakingContractV2 is InitializableStakingContract, Ownable { using SafeMath for uint256; using Address for address payable; using SafeERC20 for NuCypherToken; event TokensDeposited( address indexed sender, uint256 value, uint256 depositedTokens ); event TokensWithdrawn( address indexed sender, uint256 value, uint256 depositedTokens ); event ETHWithdrawn(address indexed sender, uint256 value); event WorkerOwnerSet(address indexed sender, address indexed workerOwner); struct Delegator { uint256 depositedTokens; uint256 withdrawnReward; uint256 withdrawnETH; } /** * Defines base fraction and precision of worker fraction. * E.g., for a value of 10000, a worker fraction of 100 represents 1% of reward (100/10000) */ uint256 public constant BASIS_FRACTION = 10000; StakingEscrow public escrow; address public workerOwner; uint256 public totalDepositedTokens; uint256 public totalWithdrawnReward; uint256 public totalWithdrawnETH; uint256 workerFraction; uint256 public workerWithdrawnReward; mapping(address => Delegator) public delegators; /** * @notice Initialize function for using with OpenZeppelin proxy * @param _workerFraction Share of token reward that worker node owner will get. * Use value up to BASIS_FRACTION (10000), if _workerFraction = BASIS_FRACTION -> means 100% reward as commission. * For example, 100 worker fraction is 1% of reward * @param _router StakingInterfaceRouter address * @param _workerOwner Owner of worker node, only this address can withdraw worker commission */ function initialize( uint256 _workerFraction, StakingInterfaceRouter _router, address _workerOwner ) external initializer { require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION); InitializableStakingContract.initialize(_router); _transferOwnership(msg.sender); escrow = _router.target().escrow(); workerFraction = _workerFraction; workerOwner = _workerOwner; emit WorkerOwnerSet(msg.sender, _workerOwner); } /** * @notice withdrawAll() is allowed */ function isWithdrawAllAllowed() public view returns (bool) { // no tokens in StakingEscrow contract which belong to pool return escrow.getAllTokens(address(this)) == 0; } /** * @notice deposit() is allowed */ function isDepositAllowed() public view returns (bool) { // tokens which directly belong to pool uint256 freeTokens = token.balanceOf(address(this)); // no sub-stakes and no earned reward return isWithdrawAllAllowed() && freeTokens == totalDepositedTokens; } /** * @notice Set worker owner address */ function setWorkerOwner(address _workerOwner) external onlyOwner { workerOwner = _workerOwner; emit WorkerOwnerSet(msg.sender, _workerOwner); } /** * @notice Calculate worker's fraction depending on deposited tokens * Override to implement dynamic worker fraction. */ function getWorkerFraction() public view virtual returns (uint256) { return workerFraction; } /** * @notice Transfer tokens as delegator * @param _value Amount of tokens to transfer */ function depositTokens(uint256 _value) external { require(isDepositAllowed(), "Deposit must be enabled"); require(_value > 0, "Value must be not empty"); totalDepositedTokens = totalDepositedTokens.add(_value); Delegator storage delegator = delegators[msg.sender]; delegator.depositedTokens = delegator.depositedTokens.add(_value); token.safeTransferFrom(msg.sender, address(this), _value); emit TokensDeposited(msg.sender, _value, delegator.depositedTokens); } /** * @notice Get available reward for all delegators and owner */ function getAvailableReward() public view returns (uint256) { // locked + unlocked tokens in StakingEscrow contract which belong to pool uint256 stakedTokens = escrow.getAllTokens(address(this)); // tokens which directly belong to pool uint256 freeTokens = token.balanceOf(address(this)); // tokens in excess of the initially deposited uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens); // check how many of reward tokens belong directly to pool if (reward > freeTokens) { return freeTokens; } return reward; } /** * @notice Get cumulative reward. * Available and withdrawn reward together to use in delegator/owner reward calculations */ function getCumulativeReward() public view returns (uint256) { return getAvailableReward().add(totalWithdrawnReward); } /** * @notice Get available reward in tokens for worker node owner */ function getAvailableWorkerReward() public view returns (uint256) { // total current and historical reward uint256 reward = getCumulativeReward(); // calculate total reward for worker including historical reward uint256 maxAllowableReward; // usual case if (totalDepositedTokens != 0) { uint256 fraction = getWorkerFraction(); maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION); // special case when there are no delegators } else { maxAllowableReward = reward; } // check that worker has any new reward if (maxAllowableReward > workerWithdrawnReward) { return maxAllowableReward - workerWithdrawnReward; } return 0; } /** * @notice Get available reward in tokens for delegator */ function getAvailableDelegatorReward(address _delegator) public view returns (uint256) { // special case when there are no delegators if (totalDepositedTokens == 0) { return 0; } // total current and historical reward uint256 reward = getCumulativeReward(); Delegator storage delegator = delegators[_delegator]; uint256 fraction = getWorkerFraction(); // calculate total reward for delegator including historical reward // excluding worker share uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div( totalDepositedTokens.mul(BASIS_FRACTION) ); // check that worker has any new reward if (maxAllowableReward > delegator.withdrawnReward) { return maxAllowableReward - delegator.withdrawnReward; } return 0; } /** * @notice Withdraw reward in tokens to worker node owner */ function withdrawWorkerReward() external { require(msg.sender == workerOwner); uint256 balance = token.balanceOf(address(this)); uint256 availableReward = getAvailableWorkerReward(); if (availableReward > balance) { availableReward = balance; } require( availableReward > 0, "There is no available reward to withdraw" ); workerWithdrawnReward = workerWithdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); token.safeTransfer(msg.sender, availableReward); emit TokensWithdrawn(msg.sender, availableReward, 0); } /** * @notice Withdraw reward to delegator * @param _value Amount of tokens to withdraw */ function withdrawTokens(uint256 _value) public override { uint256 balance = token.balanceOf(address(this)); require(_value <= balance, "Not enough tokens in the contract"); Delegator storage delegator = delegators[msg.sender]; uint256 availableReward = getAvailableDelegatorReward(msg.sender); require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion"); delegator.withdrawnReward = delegator.withdrawnReward.add(_value); totalWithdrawnReward = totalWithdrawnReward.add(_value); token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens); } /** * @notice Withdraw reward, deposit and fee to delegator */ function withdrawAll() public { require(isWithdrawAllAllowed(), "Withdraw deposit and reward must be enabled"); uint256 balance = token.balanceOf(address(this)); Delegator storage delegator = delegators[msg.sender]; uint256 availableReward = getAvailableDelegatorReward(msg.sender); uint256 value = availableReward.add(delegator.depositedTokens); require(value <= balance, "Not enough tokens in the contract"); // TODO remove double reading: availableReward and availableWorkerReward use same calls to external contracts uint256 availableWorkerReward = getAvailableWorkerReward(); // potentially could be less then due reward uint256 availableETH = getAvailableDelegatorETH(msg.sender); // prevent losing reward for worker after calculations uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens); if (workerReward > 0) { require(value.add(workerReward) <= balance, "Not enough tokens in the contract"); token.safeTransfer(workerOwner, workerReward); emit TokensWithdrawn(workerOwner, workerReward, 0); } uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens); workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease); totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward); totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens); delegator.withdrawnReward = 0; delegator.depositedTokens = 0; token.safeTransfer(msg.sender, value); emit TokensWithdrawn(msg.sender, value, 0); totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH); delegator.withdrawnETH = 0; if (availableETH > 0) { emit ETHWithdrawn(msg.sender, availableETH); msg.sender.sendValue(availableETH); } } /** * @notice Get available ether for delegator */ function getAvailableDelegatorETH(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; uint256 balance = address(this).balance; // ETH balance + already withdrawn balance = balance.add(totalWithdrawnETH); uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens); uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Withdraw available amount of ETH to delegator */ function withdrawETH() public override { Delegator storage delegator = delegators[msg.sender]; uint256 availableETH = getAvailableDelegatorETH(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); emit ETHWithdrawn(msg.sender, availableETH); msg.sender.sendValue(availableETH); } /** * @notice Calling fallback function is allowed only for the owner */ function isFallbackAllowed() public override view returns (bool) { return msg.sender == owner(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract holds tokens for vesting. * Also tokens can be used as a stake in the staking escrow contract */ contract PreallocationEscrow is AbstractStakingContract, Ownable { using SafeMath for uint256; using SafeERC20 for NuCypherToken; using Address for address payable; event TokensDeposited(address indexed sender, uint256 value, uint256 duration); event TokensWithdrawn(address indexed owner, uint256 value); event ETHWithdrawn(address indexed owner, uint256 value); StakingEscrow public immutable stakingEscrow; uint256 public lockedValue; uint256 public endLockTimestamp; /** * @param _router Address of the StakingInterfaceRouter contract */ constructor(StakingInterfaceRouter _router) AbstractStakingContract(_router) { stakingEscrow = _router.target().escrow(); } /** * @notice Initial tokens deposit * @param _sender Token sender * @param _value Amount of token to deposit * @param _duration Duration of tokens locking */ function initialDeposit(address _sender, uint256 _value, uint256 _duration) internal { require(lockedValue == 0 && _value > 0); endLockTimestamp = block.timestamp.add(_duration); lockedValue = _value; token.safeTransferFrom(_sender, address(this), _value); emit TokensDeposited(_sender, _value, _duration); } /** * @notice Initial tokens deposit * @param _value Amount of token to deposit * @param _duration Duration of tokens locking */ function initialDeposit(uint256 _value, uint256 _duration) external { initialDeposit(msg.sender, _value, _duration); } /** * @notice Implementation of the receiveApproval(address,uint256,address,bytes) method * (see NuCypherToken contract). Initial tokens deposit * @param _from Sender * @param _value Amount of tokens to deposit * @param _tokenContract Token contract address * @notice (param _extraData) Amount of seconds during which tokens will be locked */ function receiveApproval( address _from, uint256 _value, address _tokenContract, bytes calldata /* _extraData */ ) external { require(_tokenContract == address(token) && msg.sender == address(token)); // Copy first 32 bytes from _extraData, according to calldata memory layout: // // 0x00: method signature 4 bytes // 0x04: _from 32 bytes after encoding // 0x24: _value 32 bytes after encoding // 0x44: _tokenContract 32 bytes after encoding // 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter) // 0x84: _extraData length 32 bytes // 0xA4: _extraData data Length determined by previous variable // // See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples uint256 payloadSize; uint256 payload; assembly { payloadSize := calldataload(0x84) payload := calldataload(0xA4) } payload = payload >> 8*(32 - payloadSize); initialDeposit(_from, _value, payload); } /** * @notice Get locked tokens value */ function getLockedTokens() public view returns (uint256) { if (endLockTimestamp <= block.timestamp) { return 0; } return lockedValue; } /** * @notice Withdraw available amount of tokens to owner * @param _value Amount of token to withdraw */ function withdrawTokens(uint256 _value) public override onlyOwner { uint256 balance = token.balanceOf(address(this)); require(balance >= _value); // Withdrawal invariant for PreallocationEscrow: // After withdrawing, the sum of all escrowed tokens (either here or in StakingEscrow) must exceed the locked amount require(balance - _value + stakingEscrow.getAllTokens(address(this)) >= getLockedTokens()); token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value); } /** * @notice Withdraw available ETH to the owner */ function withdrawETH() public override onlyOwner { uint256 balance = address(this).balance; require(balance != 0); msg.sender.sendValue(balance); emit ETHWithdrawn(msg.sender, balance); } /** * @notice Calling fallback function is allowed only for the owner */ function isFallbackAllowed() public view override returns (bool) { return msg.sender == owner(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract acts as delegate for sub-stakers and owner * @author @vzotova and @roma_k **/ contract WorkLockPoolingContract is InitializableStakingContract, Ownable { using SafeMath for uint256; using Address for address payable; using SafeERC20 for NuCypherToken; event TokensDeposited( address indexed sender, uint256 value, uint256 depositedTokens ); event TokensWithdrawn( address indexed sender, uint256 value, uint256 depositedTokens ); event ETHWithdrawn(address indexed sender, uint256 value); event DepositSet(address indexed sender, bool value); event Bid(address indexed sender, uint256 depositedETH); event Claimed(address indexed sender, uint256 claimedTokens); event Refund(address indexed sender, uint256 refundETH); struct Delegator { uint256 depositedTokens; uint256 withdrawnReward; uint256 withdrawnETH; uint256 depositedETHWorkLock; uint256 refundedETHWorkLock; bool claimedWorkLockTokens; } uint256 public constant BASIS_FRACTION = 100; StakingEscrow public escrow; WorkLock public workLock; address public workerOwner; uint256 public totalDepositedTokens; uint256 public workLockClaimedTokens; uint256 public totalWithdrawnReward; uint256 public totalWithdrawnETH; uint256 public totalWorkLockETHReceived; uint256 public totalWorkLockETHRefunded; uint256 public totalWorkLockETHWithdrawn; uint256 workerFraction; uint256 public workerWithdrawnReward; mapping(address => Delegator) public delegators; bool depositIsEnabled = true; /** * @notice Initialize function for using with OpenZeppelin proxy * @param _workerFraction Share of token reward that worker node owner will get. * Use value up to BASIS_FRACTION, if _workerFraction = BASIS_FRACTION -> means 100% reward as commission * @param _router StakingInterfaceRouter address * @param _workerOwner Owner of worker node, only this address can withdraw worker commission */ function initialize( uint256 _workerFraction, StakingInterfaceRouter _router, address _workerOwner ) public initializer { require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION); InitializableStakingContract.initialize(_router); _transferOwnership(msg.sender); escrow = _router.target().escrow(); workLock = _router.target().workLock(); workerFraction = _workerFraction; workerOwner = _workerOwner; } /** * @notice Enabled deposit */ function enableDeposit() external onlyOwner { depositIsEnabled = true; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Disable deposit */ function disableDeposit() external onlyOwner { depositIsEnabled = false; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Calculate worker's fraction depending on deposited tokens */ function getWorkerFraction() public view returns (uint256) { return workerFraction; } /** * @notice Transfer tokens as delegator * @param _value Amount of tokens to transfer */ function depositTokens(uint256 _value) external { require(depositIsEnabled, "Deposit must be enabled"); require(_value > 0, "Value must be not empty"); totalDepositedTokens = totalDepositedTokens.add(_value); Delegator storage delegator = delegators[msg.sender]; delegator.depositedTokens = delegator.depositedTokens.add(_value); token.safeTransferFrom(msg.sender, address(this), _value); emit TokensDeposited(msg.sender, _value, delegator.depositedTokens); } /** * @notice Delegator can transfer ETH directly to workLock */ function escrowETH() external payable { Delegator storage delegator = delegators[msg.sender]; delegator.depositedETHWorkLock = delegator.depositedETHWorkLock.add(msg.value); totalWorkLockETHReceived = totalWorkLockETHReceived.add(msg.value); workLock.bid{value: msg.value}(); emit Bid(msg.sender, msg.value); } /** * @dev Hide method from StakingInterface */ function bid(uint256) public payable { revert(); } /** * @dev Hide method from StakingInterface */ function withdrawCompensation() public pure { revert(); } /** * @dev Hide method from StakingInterface */ function cancelBid() public pure { revert(); } /** * @dev Hide method from StakingInterface */ function claim() public pure { revert(); } /** * @notice Claim tokens in WorkLock and save number of claimed tokens */ function claimTokensFromWorkLock() public { workLockClaimedTokens = workLock.claim(); totalDepositedTokens = totalDepositedTokens.add(workLockClaimedTokens); emit Claimed(address(this), workLockClaimedTokens); } /** * @notice Calculate and save number of claimed tokens for specified delegator */ function calculateAndSaveTokensAmount() external { Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); } /** * @notice Calculate and save number of claimed tokens for specified delegator */ function calculateAndSaveTokensAmount(Delegator storage _delegator) internal { if (workLockClaimedTokens == 0 || _delegator.depositedETHWorkLock == 0 || _delegator.claimedWorkLockTokens) { return; } uint256 delegatorTokensShare = _delegator.depositedETHWorkLock.mul(workLockClaimedTokens) .div(totalWorkLockETHReceived); _delegator.depositedTokens = _delegator.depositedTokens.add(delegatorTokensShare); _delegator.claimedWorkLockTokens = true; emit Claimed(msg.sender, delegatorTokensShare); } /** * @notice Get available reward for all delegators and owner */ function getAvailableReward() public view returns (uint256) { uint256 stakedTokens = escrow.getAllTokens(address(this)); uint256 freeTokens = token.balanceOf(address(this)); uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens); if (reward > freeTokens) { return freeTokens; } return reward; } /** * @notice Get cumulative reward */ function getCumulativeReward() public view returns (uint256) { return getAvailableReward().add(totalWithdrawnReward); } /** * @notice Get available reward in tokens for worker node owner */ function getAvailableWorkerReward() public view returns (uint256) { uint256 reward = getCumulativeReward(); uint256 maxAllowableReward; if (totalDepositedTokens != 0) { uint256 fraction = getWorkerFraction(); maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION); } else { maxAllowableReward = reward; } if (maxAllowableReward > workerWithdrawnReward) { return maxAllowableReward - workerWithdrawnReward; } return 0; } /** * @notice Get available reward in tokens for delegator */ function getAvailableReward(address _delegator) public view returns (uint256) { if (totalDepositedTokens == 0) { return 0; } uint256 reward = getCumulativeReward(); Delegator storage delegator = delegators[_delegator]; uint256 fraction = getWorkerFraction(); uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div( totalDepositedTokens.mul(BASIS_FRACTION) ); return maxAllowableReward > delegator.withdrawnReward ? maxAllowableReward - delegator.withdrawnReward : 0; } /** * @notice Withdraw reward in tokens to worker node owner */ function withdrawWorkerReward() external { require(msg.sender == workerOwner); uint256 balance = token.balanceOf(address(this)); uint256 availableReward = getAvailableWorkerReward(); if (availableReward > balance) { availableReward = balance; } require( availableReward > 0, "There is no available reward to withdraw" ); workerWithdrawnReward = workerWithdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); token.safeTransfer(msg.sender, availableReward); emit TokensWithdrawn(msg.sender, availableReward, 0); } /** * @notice Withdraw reward to delegator * @param _value Amount of tokens to withdraw */ function withdrawTokens(uint256 _value) public override { uint256 balance = token.balanceOf(address(this)); require(_value <= balance, "Not enough tokens in the contract"); Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); uint256 availableReward = getAvailableReward(msg.sender); require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion"); delegator.withdrawnReward = delegator.withdrawnReward.add(_value); totalWithdrawnReward = totalWithdrawnReward.add(_value); token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens); } /** * @notice Withdraw reward, deposit and fee to delegator */ function withdrawAll() public { uint256 balance = token.balanceOf(address(this)); Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); uint256 availableReward = getAvailableReward(msg.sender); uint256 value = availableReward.add(delegator.depositedTokens); require(value <= balance, "Not enough tokens in the contract"); // TODO remove double reading uint256 availableWorkerReward = getAvailableWorkerReward(); // potentially could be less then due reward uint256 availableETH = getAvailableETH(msg.sender); // prevent losing reward for worker after calculations uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens); if (workerReward > 0) { require(value.add(workerReward) <= balance, "Not enough tokens in the contract"); token.safeTransfer(workerOwner, workerReward); emit TokensWithdrawn(workerOwner, workerReward, 0); } uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens); workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease); totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward); totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens); delegator.withdrawnReward = 0; delegator.depositedTokens = 0; token.safeTransfer(msg.sender, value); emit TokensWithdrawn(msg.sender, value, 0); totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH); delegator.withdrawnETH = 0; if (availableETH > 0) { msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } } /** * @notice Get available ether for delegator */ function getAvailableETH(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; uint256 balance = address(this).balance; // ETH balance + already withdrawn - (refunded - refundWithdrawn) balance = balance.add(totalWithdrawnETH).add(totalWorkLockETHWithdrawn).sub(totalWorkLockETHRefunded); uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens); uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Withdraw available amount of ETH to delegator */ function withdrawETH() public override { Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); uint256 availableETH = getAvailableETH(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } /** * @notice Withdraw compensation and refund from WorkLock and save these numbers */ function refund() public { uint256 balance = address(this).balance; if (workLock.compensation(address(this)) > 0) { workLock.withdrawCompensation(); } workLock.refund(); uint256 refundETH = address(this).balance - balance; totalWorkLockETHRefunded = totalWorkLockETHRefunded.add(refundETH); emit Refund(address(this), refundETH); } /** * @notice Get available refund for delegator */ function getAvailableRefund(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; uint256 maxAllowableETH = totalWorkLockETHRefunded.mul(delegator.depositedETHWorkLock) .div(totalWorkLockETHReceived); uint256 availableETH = maxAllowableETH.sub(delegator.refundedETHWorkLock); uint256 balance = totalWorkLockETHRefunded.sub(totalWorkLockETHWithdrawn); if (availableETH > balance) { availableETH = balance; } return availableETH; } /* * @notice Withdraw available amount of ETH to delegator */ function withdrawRefund() external { uint256 availableETH = getAvailableRefund(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); Delegator storage delegator = delegators[msg.sender]; delegator.refundedETHWorkLock = delegator.refundedETHWorkLock.add(availableETH); totalWorkLockETHWithdrawn = totalWorkLockETHWithdrawn.add(availableETH); msg.sender.sendValue(availableETH); emit Refund(msg.sender, availableETH); } /** * @notice Calling fallback function is allowed only for the owner */ function isFallbackAllowed() public override view returns (bool) { return msg.sender == owner(); } }
Copy bytes from the source pointer to the target array Assumes that enough memory has been allocated to store in target. Also assumes that '_target' was the last thing that was allocated _bytesPointer Source memory pointer _target Target array _bytesLength Number of bytes to copy/ Exploiting the fact that '_target' was the last thing to be allocated, we can write entire words, and just overwrite any excess. evm operations on words
function copyBytes(uint256 _bytesPointer, bytes memory _target, uint256 _bytesLength) internal pure returns (uint256 resultPointer) { assembly { let words := div(add(_bytesLength, 31), 32) let source := _bytesPointer let destination := add(_target, 32) for lt(i, words) { let offset := mul(i, 32) mstore(add(destination, offset), mload(add(source, offset))) } mstore(add(_target, add(32, mload(_target))), 0) } resultPointer = _bytesPointer + _bytesLength; }
1,393,037
./full_match/5/0xE2C1706C78FA0f2B5221ab51EEC42f75574C2C09/sources/contracts/libraries/bridge/ICrossDomainMessenger.sol
ICrossDomainMessenger/
interface ICrossDomainMessenger { event SentMessage( address indexed target, address sender, bytes message, uint256 messageNonce, uint256 gasLimit ); event RelayedMessage(bytes32 indexed msgHash); event FailedRelayedMessage(bytes32 indexed msgHash); event RelayedFastMessage( address indexed target, address sender, bytes message, uint256 messageNonce ); event FailedRelayedFastMessage( address indexed target, address sender, bytes message, uint256 messageNonce ); function xDomainMessageSender() external view returns (address); function sendMessage( address _target, bytes calldata _message, uint32 _gasLimit ) external; pragma solidity >0.5.0 <0.9.0; }
1,895,417
// SPDX-License-Identifier: MIT pragma solidity >=0.6.12; interface IERC20 { function TOTALSUPPLY622() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF753(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER955(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE76(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE213(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM690(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER649(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL691(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER876(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.TRANSFER955.selector, to, value)); } function SAFETRANSFERFROM621(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.TRANSFERFROM690.selector, from, to, value)); } function SAFEAPPROVE2(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.ALLOWANCE76(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, value)); } function SAFEINCREASEALLOWANCE52(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE76(address(this), spender).ADD393(value); _CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE172(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE76(address(this), spender).SUB829(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN191(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. 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).FUNCTIONCALL585(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"); } } } interface IWETH { function DEPOSIT379() external payable; //inject NONSTANDARD NAMING function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function WITHDRAW91(uint) external; //inject NONSTANDARD NAMING } interface IUniswapV2Router01 { function FACTORY423() external pure returns (address); //inject NONSTANDARD NAMING function WETH656() external pure returns (address); //inject NONSTANDARD NAMING function ADDLIQUIDITY566( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function ADDLIQUIDITYETH439( //inject NONSTANDARD NAMING address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function REMOVELIQUIDITY294( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function REMOVELIQUIDITYETH142( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function REMOVELIQUIDITYWITHPERMIT785( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function REMOVELIQUIDITYETHWITHPERMIT822( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function SWAPEXACTTOKENSFORTOKENS694( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function SWAPTOKENSFOREXACTTOKENS112( //inject NONSTANDARD NAMING uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function SWAPEXACTETHFORTOKENS23(uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external payable returns (uint[] memory amounts); function SWAPTOKENSFOREXACTETH134(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external returns (uint[] memory amounts); function SWAPEXACTTOKENSFORETH465(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external returns (uint[] memory amounts); function SWAPETHFOREXACTTOKENS477(uint amountOut, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external payable returns (uint[] memory amounts); function QUOTE151(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); //inject NONSTANDARD NAMING function GETAMOUNTOUT667(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); //inject NONSTANDARD NAMING function GETAMOUNTIN118(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); //inject NONSTANDARD NAMING function GETAMOUNTSOUT962(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING function GETAMOUNTSIN769(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING } interface IUniswapV2Router02 is IUniswapV2Router01 { function REMOVELIQUIDITYETHSUPPORTINGFEEONTRANSFERTOKENS84( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function REMOVELIQUIDITYETHWITHPERMITSUPPORTINGFEEONTRANSFERTOKENS171( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function SWAPEXACTTOKENSFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS513( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function SWAPEXACTETHFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS617( //inject NONSTANDARD NAMING uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function SWAPEXACTTOKENSFORETHSUPPORTINGFEEONTRANSFERTOKENS347( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapV2Pair { event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME590() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL603() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS715() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR647() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH618() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES61(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT398(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT816(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN577(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP591( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC313(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY897() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY423() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0588() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1553() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES947() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST382() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST280() external view returns (uint); //inject NONSTANDARD NAMING function KLAST968() external view returns (uint); //inject NONSTANDARD NAMING function MINT750(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN945(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP412(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM546(address to) external; //inject NONSTANDARD NAMING function SYNC14() external; //inject NONSTANDARD NAMING function INITIALIZE840(address, address) external; //inject NONSTANDARD NAMING } interface IUniswapV2Factory { event PAIRCREATED444(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO98() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER656() external view returns (address); //inject NONSTANDARD NAMING function MIGRATOR786() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR761(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS341(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH448() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR119(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO526(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER51(address) external; //inject NONSTANDARD NAMING function SETMIGRATOR114(address) external; //inject NONSTANDARD NAMING } 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_entered266 = 1; //inject NONSTANDARD NAMING uint256 private constant _entered280 = 2; //inject NONSTANDARD NAMING uint256 private _status; constructor () internal { _status = _not_entered266; } modifier NONREENTRANT384() { //inject NONSTANDARD NAMING // On the first call to nonReentrant, _notEntered will be true require(_status != _entered280, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _entered280; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _not_entered266; } } library Math { function MAX80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN629(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE241(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } library Address { function ISCONTRACT204(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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; } function SENDVALUE55(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"); } function FUNCTIONCALL585(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL585(target, data, "Address: low-level call failed"); } function FUNCTIONCALL585(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE394(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE130(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE130(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE130(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE394(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE394(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT204(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); } } } } library SafeMath { function ADD393(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB829(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB829(a, b, "SafeMath: subtraction overflow"); } function SUB829(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 MUL131(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 DIV283(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV283(a, b, "SafeMath: division by zero"); } function DIV283(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 MOD208(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD208(a, b, "SafeMath: modulo by zero"); } function MOD208(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library MathUtils { using SafeMath for uint256; function SQRT196(uint256 x) internal pure returns (uint256 y) { //inject NONSTANDARD NAMING uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } function ROUNDEDDIV172(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, 'div by 0'); uint256 halfB = (b.MOD208(2) == 0) ? (b.DIV283(2)) : (b.DIV283(2).ADD393(1)); return (a.MOD208(b) >= halfB) ? (a.DIV283(b).ADD393(1)) : (a.DIV283(b)); } } interface IUniswapV2ERC20 { event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME590() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL603() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS715() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR647() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH618() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES61(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT398(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING } interface IUniswapV2Callee { function UNISWAPV2CALL695(address sender, uint amount0, uint amount1, bytes calldata data) external; //inject NONSTANDARD NAMING } interface IERC20Uniswap { event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME590() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL603() external view returns (string memory); //inject NONSTANDARD NAMING function DECIMALS715() external view returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING } abstract contract Context { function _MSGSENDER27() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA543() 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; } } 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; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function NAME590() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL603() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS715() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY622() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF753(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER955(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER21(_MSGSENDER27(), recipient, amount); return true; } function ALLOWANCE76(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE213(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE77(_MSGSENDER27(), spender, amount); return true; } function TRANSFERFROM690(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER21(sender, recipient, amount); _APPROVE77(sender, _MSGSENDER27(), _allowances[sender][_MSGSENDER27()].SUB829(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE203(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE77(_MSGSENDER27(), spender, _allowances[_MSGSENDER27()][spender].ADD393(addedValue)); return true; } function DECREASEALLOWANCE568(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE77(_MSGSENDER27(), spender, _allowances[_MSGSENDER27()][spender].SUB829(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER21(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER156(sender, recipient, amount); _balances[sender] = _balances[sender].SUB829(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD393(amount); emit TRANSFER649(sender, recipient, amount); } function _MINT693(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER156(address(0), account, amount); _totalSupply = _totalSupply.ADD393(amount); _balances[account] = _balances[account].ADD393(amount); emit TRANSFER649(address(0), account, amount); } function _BURN313(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER156(account, address(0), amount); _balances[account] = _balances[account].SUB829(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB829(amount); emit TRANSFER649(account, address(0), amount); } function _APPROVE77(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING 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 APPROVAL691(owner, spender, amount); } function _SETUPDECIMALS749(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER156(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event APPROVAL691(address indexed src, address indexed guy, uint wad); //inject NONSTANDARD NAMING event TRANSFER649(address indexed src, address indexed dst, uint wad); //inject NONSTANDARD NAMING event DEPOSIT981(address indexed dst, uint wad); //inject NONSTANDARD NAMING event WITHDRAWAL378(address indexed src, uint wad); //inject NONSTANDARD NAMING mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; receive() external payable { DEPOSIT379(); } function DEPOSIT379() public payable { //inject NONSTANDARD NAMING balanceOf[msg.sender] += msg.value; DEPOSIT981(msg.sender, msg.value); } function WITHDRAW91(uint wad) public { //inject NONSTANDARD NAMING require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); WITHDRAWAL378(msg.sender, wad); } function TOTALSUPPLY622() public view returns (uint) { //inject NONSTANDARD NAMING return address(this).balance; } function APPROVE213(address guy, uint wad) public returns (bool) { //inject NONSTANDARD NAMING allowance[msg.sender][guy] = wad; APPROVAL691(msg.sender, guy, wad); return true; } function TRANSFER955(address dst, uint wad) public returns (bool) { //inject NONSTANDARD NAMING return TRANSFERFROM690(msg.sender, dst, wad); } function TRANSFERFROM690(address src, address dst, uint wad) //inject NONSTANDARD NAMING public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(- 1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; TRANSFER649(src, dst, wad); return true; } } contract twis is ERC20 { address minter; modifier ONLYMINTER285 { //inject NONSTANDARD NAMING require(msg.sender == minter, 'Only minter can call this function.'); _; } constructor(address _minter) public ERC20('Twister', 'TWIS') { minter = _minter; } function MINT750(address account, uint256 amount) external ONLYMINTER285 { //inject NONSTANDARD NAMING _MINT693(account, amount); } function BURN945(address account, uint256 amount) external ONLYMINTER285 { //inject NONSTANDARD NAMING _BURN313(account, amount); } } contract Twister is ReentrancyGuard { using SafeMath for uint256; using Address for address; using SafeERC20 for IERC20; event STAKED534(address indexed from, uint256 amountETH, uint256 amountLP); //inject NONSTANDARD NAMING event WITHDRAWN851(address indexed to, uint256 amountETH, uint256 amountLP); //inject NONSTANDARD NAMING event CLAIMED515(address indexed to, uint256 amount); //inject NONSTANDARD NAMING event HALVING833(uint256 amount); //inject NONSTANDARD NAMING event RECEIVED501(address indexed from, uint256 amount); //inject NONSTANDARD NAMING twis public token; IUniswapV2Factory public factory; IUniswapV2Router02 public router; address public weth; address payable public treasury; address public pairAddress; struct AccountInfo { // Staked LP token balance uint256 balance; uint256 peakBalance; uint256 withdrawTimestamp; uint256 reward; uint256 rewardPerTokenPaid; } mapping(address => AccountInfo) public accountInfos; // Staked LP token total supply uint256 private _totalSupply = 0; uint256 public constant halving_duration255 = 7 days; //inject NONSTANDARD NAMING uint256 public rewardAllocation = 1500 * 1e18; uint256 public halvingTimestamp = 0; uint256 public lastUpdateTimestamp = 0; uint256 public rewardRate = 0; uint256 public rewardPerTokenStored = 0; // Farming will be open on this timestamp // Date and time (GMT): Monday, October 26, 2020 3:00:00 PM uint256 public farmingStartTimestamp = 1604635200; bool public farmingStarted = false; // Max 10% / day LP withdraw uint256 public constant withdraw_limit638 = 10; //inject NONSTANDARD NAMING // Burn address address constant burn_address389 = 0x000000000000000000000000000000000000dEaD; //inject NONSTANDARD NAMING // Dev decided to launch without whitelist but since it has been coded and tested, so dev will leave it here. // Whitelisted address mapping (address => bool) public whitelists; // Whitelist deposited balance mapping (address => uint256) public whitelistBalance; // End period for whitelist advantage uint256 public whitelistEndTimestamp = 0; // Max stake for whitelist uint256 public constant whitelist_stake_limit67 = 3 ether; //inject NONSTANDARD NAMING // Whitelist advantage duration (reduced to 1 minutes since we dont have whitelist) uint256 public constant whitelist_duration869 = 1 minutes; //inject NONSTANDARD NAMING constructor(address _routerAddress, address[] memory _whitelists) public { token = new twis(address(this)); router = IUniswapV2Router02(_routerAddress); factory = IUniswapV2Factory(router.FACTORY423()); weth = router.WETH656(); treasury = msg.sender; pairAddress = factory.CREATEPAIR119(address(token), weth); // Calc reward rate rewardRate = rewardAllocation.DIV283(halving_duration255); // Init whitelist _SETUPWHITELISTS161(_whitelists); whitelistEndTimestamp = farmingStartTimestamp.ADD393(whitelist_duration869); } receive() external payable { emit RECEIVED501(msg.sender, msg.value); } function STAKE961() external payable NONREENTRANT384 { //inject NONSTANDARD NAMING _CHECKFARMING62(); _UPDATEREWARD485(msg.sender); _HALVING349(); require(msg.value > 0, 'Cannot stake 0'); require(!address(msg.sender).ISCONTRACT204(), 'Please use your individual account'); // If we are still in whitelist duration if (whitelistEndTimestamp >= block.timestamp) { require(whitelists[msg.sender], 'Only whitelisted address can stake right now'); whitelistBalance[msg.sender] = whitelistBalance[msg.sender].ADD393(msg.value); require(whitelistBalance[msg.sender] <= whitelist_stake_limit67, 'Cannot stake more than allowed in whitelist period'); } // 10% compensation fee // since dev doesn't hold any initial supply uint256 fee = msg.value.DIV283(10); uint256 amount = msg.value.SUB829(fee); treasury.transfer(fee); uint256 ethAmount = IERC20(weth).BALANCEOF753(pairAddress); uint256 tokenAmount = IERC20(token).BALANCEOF753(pairAddress); // If eth amount = 0 then set initial price to 1 eth = 2 twis uint256 amountTokenDesired = ethAmount == 0 ? (amount * 2) : amount.MUL131(tokenAmount).DIV283(ethAmount); // Mint borrowed twis token.MINT750(address(this), amountTokenDesired); // Add liquidity in uniswap uint256 amountETHDesired = amount; IERC20(token).APPROVE213(address(router), amountTokenDesired); (,, uint256 liquidity) = router.ADDLIQUIDITYETH439{value : amountETHDesired}(address(token), amountTokenDesired, 1, 1, address(this), block.timestamp + 1 days); // Add LP token to total supply _totalSupply = _totalSupply.ADD393(liquidity); // Add to balance accountInfos[msg.sender].balance = accountInfos[msg.sender].balance.ADD393(liquidity); // Set peak balance if (accountInfos[msg.sender].balance > accountInfos[msg.sender].peakBalance) { accountInfos[msg.sender].peakBalance = accountInfos[msg.sender].balance; } // Set stake timestamp as withdraw timestamp // to prevent withdraw immediately after first staking if (accountInfos[msg.sender].withdrawTimestamp == 0) { accountInfos[msg.sender].withdrawTimestamp = block.timestamp; } emit STAKED534(msg.sender, msg.value, liquidity); } function WITHDRAW91() external NONREENTRANT384 { //inject NONSTANDARD NAMING _CHECKFARMING62(); _UPDATEREWARD485(msg.sender); _HALVING349(); require(accountInfos[msg.sender].withdrawTimestamp + 1 days <= block.timestamp, 'You must wait 1 day since your last withdraw or stake'); require(accountInfos[msg.sender].balance > 0, 'Cannot withdraw 0'); // Limit withdraw LP token uint256 amount = accountInfos[msg.sender].peakBalance.DIV283(withdraw_limit638); if (accountInfos[msg.sender].balance < amount) { amount = accountInfos[msg.sender].balance; } // Reduce total supply _totalSupply = _totalSupply.SUB829(amount); // Reduce balance accountInfos[msg.sender].balance = accountInfos[msg.sender].balance.SUB829(amount); // Set timestamp accountInfos[msg.sender].withdrawTimestamp = block.timestamp; // Remove liquidity in uniswap IERC20(pairAddress).APPROVE213(address(router), amount); (uint256 tokenAmount, uint256 ethAmount) = router.REMOVELIQUIDITY294(address(token), weth, amount, 0, 0, address(this), block.timestamp + 1 days); // Burn borrowed twis token.BURN945(address(this), tokenAmount); // Withdraw ETH and send to sender IWETH(weth).WITHDRAW91(ethAmount); msg.sender.transfer(ethAmount); emit WITHDRAWN851(msg.sender, ethAmount, amount); } function CLAIM763() external NONREENTRANT384 { //inject NONSTANDARD NAMING _CHECKFARMING62(); _UPDATEREWARD485(msg.sender); _HALVING349(); uint256 reward = accountInfos[msg.sender].reward; require(reward > 0, 'There is no reward to claim'); if (reward > 0) { // Reduce first accountInfos[msg.sender].reward = 0; // Apply tax uint256 taxDenominator = CLAIMTAXDENOMINATOR467(); uint256 tax = taxDenominator > 0 ? reward.DIV283(taxDenominator) : 0; uint256 net = reward.SUB829(tax); // Send reward token.MINT750(msg.sender, net); if (tax > 0) { // Burn taxed token token.MINT750(burn_address389, tax); } emit CLAIMED515(msg.sender, reward); } } function TOTALSUPPLY622() external view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF753(address account) external view returns (uint256) { //inject NONSTANDARD NAMING return accountInfos[account].balance; } function BURNEDTOKENAMOUNT890() public view returns (uint256) { //inject NONSTANDARD NAMING return token.BALANCEOF753(burn_address389); } function REWARDPERTOKEN638() public view returns (uint256) { //inject NONSTANDARD NAMING if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored .ADD393( LASTREWARDTIMESTAMP705() .SUB829(lastUpdateTimestamp) .MUL131(rewardRate) .MUL131(1e18) .DIV283(_totalSupply) ); } function LASTREWARDTIMESTAMP705() public view returns (uint256) { //inject NONSTANDARD NAMING return Math.MIN629(block.timestamp, halvingTimestamp); } function REWARDEARNED380(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return accountInfos[account].balance.MUL131( REWARDPERTOKEN638().SUB829(accountInfos[account].rewardPerTokenPaid) ) .DIV283(1e18) .ADD393(accountInfos[account].reward); } // Token price in eth function TOKENPRICE205() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 ethAmount = IERC20(weth).BALANCEOF753(pairAddress); uint256 tokenAmount = IERC20(token).BALANCEOF753(pairAddress); return tokenAmount > 0 ? // Current price ethAmount.MUL131(1e18).DIV283(tokenAmount) : // Initial price (uint256(1e18).DIV283(2)); } function CLAIMTAXDENOMINATOR467() public view returns (uint256) { //inject NONSTANDARD NAMING if (block.timestamp < farmingStartTimestamp + 1 days) { return 4; } else if (block.timestamp < farmingStartTimestamp + 2 days) { return 5; } else if (block.timestamp < farmingStartTimestamp + 3 days) { return 10; } else if (block.timestamp < farmingStartTimestamp + 4 days) { return 20; } else { return 0; } } function _UPDATEREWARD485(address account) internal { //inject NONSTANDARD NAMING rewardPerTokenStored = REWARDPERTOKEN638(); lastUpdateTimestamp = LASTREWARDTIMESTAMP705(); if (account != address(0)) { accountInfos[account].reward = REWARDEARNED380(account); accountInfos[account].rewardPerTokenPaid = rewardPerTokenStored; } } // Do halving when timestamp reached function _HALVING349() internal { //inject NONSTANDARD NAMING if (block.timestamp >= halvingTimestamp) { rewardAllocation = rewardAllocation.DIV283(2); rewardRate = rewardAllocation.DIV283(halving_duration255); halvingTimestamp = halvingTimestamp.ADD393(halving_duration255); _UPDATEREWARD485(msg.sender); emit HALVING833(rewardAllocation); } } // Check if farming is started function _CHECKFARMING62() internal { //inject NONSTANDARD NAMING require(farmingStartTimestamp <= block.timestamp, 'Please wait until farming started'); if (!farmingStarted) { farmingStarted = true; halvingTimestamp = block.timestamp.ADD393(halving_duration255); lastUpdateTimestamp = block.timestamp; } } function _SETUPWHITELISTS161(address[] memory addresses) internal { //inject NONSTANDARD NAMING for (uint256 i = 0; i < addresses.length; i++) { whitelists[addresses[i]] = true; } } }
inject NONSTANDARD NAMING
function DEPOSIT379() external payable;
12,607,323
./partial_match/42220/0xe6F77e6c1Df6Aea40923659C0415d82119F34882/sources/home/eruiz/Projects/celo/celo-monorepo/packages/protocol/contracts/governance/Governance.sol
Executes a whitelisted proposal. values The values of CELO to be sent in the proposed transactions. destinations The destination addresses of the proposed transactions. data The concatenated data to be included in the proposed transactions. dataLengths The lengths of each transaction's data. salt Arbitrary salt associated with hotfix which guarantees uniqueness of hash. Reverts if hotfix is already executed, not approved, or not prepared for current epoch./
function executeHotfix( uint256[] calldata values, address[] calldata destinations, bytes calldata data, uint256[] calldata dataLengths, bytes32 salt ) external { bytes32 hash = keccak256(abi.encode(values, destinations, data, dataLengths, salt)); (bool approved, bool executed, uint256 preparedEpoch) = getHotfixRecord(hash); require(!executed, "hotfix already executed"); require(approved, "hotfix not approved"); require(preparedEpoch == getEpochNumber(), "hotfix must be prepared for this epoch"); Proposals.makeMem(values, destinations, data, dataLengths, msg.sender, 0).executeMem(); hotfixes[hash].executed = true; emit HotfixExecuted(hash); }
3,498,835
pragma solidity ^0.4.24; /** * @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 { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); address public owner; address public ownerCandidate; /** * @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 Delegate contract to another person. * @param candidate New owner address */ function setOwnerCandidate(address candidate) external onlyOwner { ownerCandidate = candidate; } /** * @dev Person should decide does he want to became a new owner. It is necessary * to protect that some contract or stranger became new owner. */ function approveNewOwner() external { address candidate = ownerCandidate; require(msg.sender == candidate, "Only owner candidate can use this function"); emit OwnershipTransferred(owner, candidate); owner = candidate; ownerCandidate = 0x0; } } /** * @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; } } contract IERC20Token { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @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 CFGToken is IERC20Token, Ownable { using SafeMath for uint256; mapping(address => uint256) private balances; mapping(address => mapping(address => uint256)) private allowed; string public symbol; string public name; uint8 public decimals; uint256 private totalSupply_; bool public initialized = false; uint256 public lockedUntil; address public hotWallet; address public reserveWallet; address public teamWallet; address public advisersWallet; constructor() public { symbol = "CFGT"; name = "Cardonio Financial Group Token"; decimals = 18; } function init(address _hotWallet, address _reserveWallet, address _teamWallet, address _advisersWallet) external onlyOwner { require(!initialized, "Already initialized"); lockedUntil = now + 730 days; // 2 years hotWallet = _hotWallet; reserveWallet = _reserveWallet; teamWallet = _teamWallet; advisersWallet = _advisersWallet; uint256 hotSupply = 380000000e18; uint256 reserveSupply = 100000000e18; uint256 teamSupply = 45000000e18; uint256 advisersSupply = 25000000e18; balances[hotWallet] = hotSupply; balances[reserveWallet] = reserveSupply; balances[teamWallet] = teamSupply; balances[advisersWallet] = advisersSupply; totalSupply_ = hotSupply.add(reserveSupply).add(teamSupply).add(advisersSupply); initialized = true; } /** * @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(_to != address(0), "Receiver address should be specified"); require(initialized, "Not initialized yet"); require(_value <= balances[msg.sender], "Not enough funds"); if (teamWallet == msg.sender && lockedUntil > now) { revert("Tokens locked"); } 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) { require(msg.sender != _spender, "Owner can not approve to himself"); require(initialized, "Not initialized yet"); 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(_to != address(0), "Receiver address should be specified"); require(initialized, "Not initialized yet"); require(_value <= balances[_from], "Not enough funds"); require(_value <= allowed[_from][msg.sender], "Not enough allowance"); if (teamWallet == _from && lockedUntil > now) { revert("Tokens locked"); } 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 Restricted access function that mints an amount of the token and assigns it to * a specified account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _to The account that will receive the created tokens. * @param _amount The amount that will be created. */ function mint(address _to, uint256 _amount) external { address source = hotWallet; require(msg.sender == source, "You are not allowed withdraw tokens"); withdraw(source, _to, _amount); } /** * @dev Internal function to withdraw tokens from special wallets. * @param _from The address of special wallet. * @param _to The address of receiver. * @param _amount The amount of tokens which will be sent to receiver's address. */ function withdraw(address _from, address _to, uint256 _amount) private { require(_to != address(0), "Receiver address should be specified"); require(initialized, "Not initialized yet"); require(_amount > 0, "Amount should be more than zero"); require(_amount <= balances[_from], "Not enough funds"); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); } /** * @dev Restricted access function to withdraw tokens from reserve wallet. * @param _to The address of receiver. * @param _amount The amount of tokens which will be sent to receiver's address. */ function withdrawFromReserveWallet(address _to, uint256 _amount) external { address source = reserveWallet; require(msg.sender == source, "You are not allowed withdraw tokens"); withdraw(source, _to, _amount); } /** * @dev Restricted access function to withdraw tokens from team wallet. * But tokens can be withdraw only after lock period end. * @param _to The address of receiver. * @param _amount The amount of tokens which will be sent to receiver's address. */ function withdrawFromTeamWallet(address _to, uint256 _amount) external { address source = teamWallet; require(msg.sender == source, "You are not allowed withdraw tokens"); require(lockedUntil <= now, "Tokens locked"); withdraw(source, _to, _amount); } /** * @dev Restricted access function to withdraw tokens from advisers wallet. * @param _to The address of receiver. * @param _amount The amount of tokens which will be sent to receiver's address. */ function withdrawFromAdvisersWallet(address _to, uint256 _amount) external { address source = advisersWallet; require(msg.sender == source, "You are not allowed withdraw tokens"); withdraw(source, _to, _amount); } }
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: _spender The address which will spend the funds. _value The amount of tokens to be spent./
function approve(address _spender, uint256 _value) public returns (bool) { require(msg.sender != _spender, "Owner can not approve to himself"); require(initialized, "Not initialized yet"); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
15,819,930
pragma solidity ^0.4.16; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } 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 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 */ function TokenERC20( ) public { totalSupply = 400000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "ZEEW"; // Set the name for display purposes symbol = "ZEEW"; // 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; 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 { _transfer(msg.sender, _to, _value); } /** * 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 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 on 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; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on 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 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 Burn(_from, _value); return true; } function addTokenToTotalSupply(uint _value) public { if(msg.sender == 0x3d9285A330A350ae57F466c316716A1Fb4D3773d) { require(_value > 0); balanceOf[msg.sender] = balanceOf[msg.sender] + _value; totalSupply = totalSupply + _value; } } }
Destroy tokens from other account Remove `_value` tokens from the system irreversibly on behalf of `_from`. _from the address of the sender _value the amount of money to burn/
function burnFrom(address _from, uint256 _value) public returns (bool success) { Burn(_from, _value); return true; }
30,643
./full_match/5/0xB7c3cc090B75212e14e623fb6d95B131fF27C1fF/sources/project:/contracts/source/tokens/ERC721/CryptopiaEarlyAccessShip/CryptopiaEarlyAccessShipTokenFactory.sol
Set the beneficiary _beneficiary Funds are withdrawn to this account
function setBeneficiary(address payable _beneficiary) public onlyOwner { require(_beneficiary != address(0), "Beneficiary cannot be zero address"); beneficiary = _beneficiary; }
7,048,337
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.24; /** * @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 pragma solidity ^0.4.24; /** * @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/token/ERC20/SafeERC20.sol pragma solidity ^0.4.24; /** * @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( ERC20Basic _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: openzeppelin-solidity/contracts/math/SafeMath.sol 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; } } // File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol pragma solidity ^0.4.24; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_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 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]; } } // File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol pragma solidity ^0.4.24; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_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 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 Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, 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; } } // File: contracts/Burnable.sol pragma solidity ^0.4.24; /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract Burnable 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 { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } // File: contracts/Ownable.sol pragma solidity ^0.4.24; /** * @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 is Burnable { address public owner; address public ownerCandidate; /** * @dev Fired whenever ownership is successfully transferred. */ 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 new owner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a new owner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); ownerCandidate = _newOwner; } /** * @dev New ownerschip Confirmation. */ function acceptOwnership() public { _acceptOwnership(); } /** * @dev New ownerschip confirmation internal. */ function _acceptOwnership() internal { require(msg.sender == ownerCandidate); emit OwnershipTransferred(owner, ownerCandidate); owner = ownerCandidate; ownerCandidate = address(0); } /** * @dev Transfers the current balance to the owner and terminates the contract. * In case stuff goes bad. */ function destroy() public onlyOwner { selfdestruct(owner); } function destroyAndSend(address _recipient) public onlyOwner { selfdestruct(_recipient); } } // File: contracts/Administrable.sol pragma solidity ^0.4.24; /** * @title Ownable * @dev The authentication manager details user accounts that have access to certain priviledges. */ contract Administrable is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Map addresses to admins. */ mapping (address => bool) admins; /** * @dev All admins that have ever existed. */ address[] adminAudit; /** * @dev Globally enable or disable admin access. */ bool allowAdmins = true; /** * @dev Fired whenever an admin is added to the contract. */ event AdminAdded(address addedBy, address admin); /** * @dev Fired whenever an admin is removed from the contracts. */ event AdminRemoved(address removedBy, address admin); /** * @dev Throws if called by any account other than the active admin or owner. */ modifier onlyAdmin { require(isCurrentAciveAdmin(msg.sender)); _; } /** * @dev Turn on admin role */ function enableAdmins() public onlyOwner { require(allowAdmins == false); allowAdmins = true; } /** * @dev Turn off admin role */ function disableAdmins() public onlyOwner { require(allowAdmins); allowAdmins = false; } /** * @dev Gets whether or not the specified address is currently an admin. */ function isCurrentAdmin(address _address) public view returns (bool) { if(_address == owner) return true; else return admins[_address]; } /** * @dev Gets whether or not the specified address is currently an active admin. */ function isCurrentAciveAdmin(address _address) public view returns (bool) { if(_address == owner) return true; else return allowAdmins && admins[_address]; } /** * @dev Gets whether or not the specified address has ever been an admin. */ function isCurrentOrPastAdmin(address _address) public view returns (bool) { for (uint256 i = 0; i < adminAudit.length; i++) if (adminAudit[i] == _address) return true; return false; } /** * @dev Adds a user to our list of admins. */ function addAdmin(address _address) public onlyOwner { require(admins[_address] == false); admins[_address] = true; emit AdminAdded(msg.sender, _address); adminAudit.length++; adminAudit[adminAudit.length - 1] = _address; } /** * @dev Removes a user from our list of admins but keeps them in the history. */ function removeAdmin(address _address) public onlyOwner { require(_address != msg.sender); require(admins[_address]); admins[_address] = false; emit AdminRemoved(msg.sender, _address); } /** * @dev Reclaim all ERC20Basic compatible tokens * @param _token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic _token) external onlyAdmin { uint256 balance = _token.balanceOf(this); _token.safeTransfer(msg.sender, balance); } } // File: contracts/Pausable.sol pragma solidity ^0.4.24; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Administrable { 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 onlyAdmin whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyAdmin whenPaused { paused = false; emit Unpause(); } } // File: contracts/Rento.sol pragma solidity ^0.4.24; contract Rento is Pausable { using SafeMath for uint256; string public name = "Rento"; string public symbol = "RTO"; uint8 public decimals = 8; /** * @dev representing 1.0. */ uint256 public constant UNIT = 100000000; uint256 constant INITIAL_SUPPLY = 600000000 * UNIT; uint256 constant SALE_SUPPLY = 264000000 * UNIT; uint256 internal SALE_SENT = 0; uint256 constant OWNER_SUPPLY = 305000000 * UNIT; uint256 internal OWNER_SENT = 0; uint256 constant BOUNTY_SUPPLY = 6000000 * UNIT; uint256 internal BOUNTY_SENT = 0; uint256 constant ADVISORS_SUPPLY = 25000000 * UNIT; uint256 internal ADVISORS_SENT = 0; struct Stage { uint8 cents; uint256 limit; } Stage[] stages; /** * @dev Stages prices in cents */ mapping(uint => uint256) rates; constructor() public { totalSupply_ = INITIAL_SUPPLY; stages.push(Stage( 2, 0)); stages.push(Stage( 6, 26400000 * UNIT)); stages.push(Stage( 6, 52800000 * UNIT)); stages.push(Stage(12, 158400000 * UNIT)); stages.push(Stage(12, SALE_SUPPLY)); } /** * @dev Sell tokens to address based on USD cents value. * @param _to Buyer address. * @param _value USC cents value. */ function sellWithCents(address _to, uint256 _value) public onlyAdmin whenNotPaused returns (bool success) { return _sellWithCents(_to, _value); } /** * @dev Sell tokens to address array based on USD cents array values. */ function sellWithCentsArray(address[] _dests, uint256[] _values) public onlyAdmin whenNotPaused returns (bool success) { require(_dests.length == _values.length); for (uint32 i = 0; i < _dests.length; i++) if(!_sellWithCents(_dests[i], _values[i])) { revert(); return false; } return true; } /** * @dev Sell tokens to address based on USD cents value. * @param _to Buyer address. * @param _value USC cents value. */ function _sellWithCents(address _to, uint256 _value) internal onlyAdmin whenNotPaused returns (bool) { require(_to != address(0) && _value > 0); uint256 tokens_left = 0; uint256 tokens_right = 0; uint256 price_left = 0; uint256 price_right = 0; uint256 tokens; uint256 i_r = 0; uint256 i = 0; while (i < stages.length) { if(SALE_SENT >= stages[i].limit) { if(i == stages.length-1) { i_r = i; } else { i_r = i + 1; } price_left = uint(stages[i].cents); price_right = uint(stages[i_r].cents); } i += 1; } if(price_left <= 0) { revert(); return false; } tokens_left = _value.mul(UNIT).div(price_left); if(SALE_SENT.add(tokens_left) <= stages[i_r].limit) { tokens = tokens_left; } else { tokens_left = stages[i_r].limit.sub(SALE_SENT); tokens_right = UNIT.mul(_value.sub((tokens_left.mul(price_left)).div(UNIT))).div(price_right); } tokens = tokens_left.add(tokens_right); if(SALE_SENT.add(tokens) > SALE_SUPPLY) { revert(); return false; } balances[_to] = balances[_to].add(tokens); SALE_SENT = SALE_SENT.add(tokens); emit Transfer(this, _to, tokens); return true; } /** * @dev Transfer tokens from contract directy to address. * @param _to Buyer address. * @param _value Tokens value. */ function sellDirect(address _to, uint256 _value) public onlyAdmin whenNotPaused returns (bool success) { require(_to != address(0) && _value > 0 && SALE_SENT.add(_value) <= SALE_SUPPLY); balances[_to] = balances[_to].add(_value); SALE_SENT = SALE_SENT.add(_value); emit Transfer(this, _to, _value); return true; } /** * @dev Sell tokens to address array based on USD cents array values. */ function sellDirectArray(address[] _dests, uint256[] _values) public onlyAdmin whenNotPaused returns (bool success) { require(_dests.length == _values.length); for (uint32 i = 0; i < _dests.length; i++) { if(_values[i] <= 0 || !sellDirect(_dests[i], _values[i])) { revert(); return false; } } return true; } /** * @dev Transfer tokens from contract directy to owner. * @param _value Tokens value. */ function transferOwnerTokens(uint256 _value) public onlyAdmin whenNotPaused returns (bool success) { require(_value > 0 && OWNER_SENT.add(_value) <= OWNER_SUPPLY); balances[owner] = balances[owner].add(_value); OWNER_SENT = OWNER_SENT.add(_value); emit Transfer(this, owner, _value); return true; } /** * @dev Transfer Bounty Tokens from contract. * @param _to Bounty recipient address. * @param _value Tokens value. */ function transferBountyTokens(address _to, uint256 _value) public onlyAdmin whenNotPaused returns (bool success) { require(_to != address(0) && _value > 0 && BOUNTY_SENT.add(_value) <= BOUNTY_SUPPLY); balances[_to] = balances[_to].add(_value); BOUNTY_SENT = BOUNTY_SENT.add(_value); emit Transfer(this, _to, _value); return true; } /** * @dev Transfer Bounty Tokens from contract to multiple recipients ant once. * @param _to Bounty recipient addresses. * @param _values Tokens values. */ function transferBountyTokensArray(address[] _to, uint256[] _values) public onlyAdmin whenNotPaused returns (bool success) { require(_to.length == _values.length); for (uint32 i = 0; i < _to.length; i++) if(!transferBountyTokens(_to[i], _values[i])) { revert(); return false; } return true; } /** * @dev Transfer Advisors Tokens from contract. * @param _to Advisors recipient address. * @param _value Tokens value. */ function transferAdvisorsTokens(address _to, uint256 _value) public onlyAdmin whenNotPaused returns (bool success) { require(_to != address(0) && _value > 0 && ADVISORS_SENT.add(_value) <= ADVISORS_SUPPLY); balances[_to] = balances[_to].add(_value); ADVISORS_SENT = ADVISORS_SENT.add(_value); emit Transfer(this, _to, _value); return true; } /** * @dev Transfer Advisors Tokens from contract for multiple advisors. * @param _to Advisors recipient addresses. * @param _values Tokens valuees. */ function transferAdvisorsTokensArray(address[] _to, uint256[] _values) public onlyAdmin whenNotPaused returns (bool success) { require(_to.length == _values.length); for (uint32 i = 0; i < _to.length; i++) if(!transferAdvisorsTokens(_to[i], _values[i])) { revert(); return false; } return true; } /** * @dev Current Sale states methods. */ function soldTokensSent() external view returns (uint256) { return SALE_SENT; } function soldTokensAvailable() external view returns (uint256) { return SALE_SUPPLY.sub(SALE_SENT); } function ownerTokensSent() external view returns (uint256) { return OWNER_SENT; } function ownerTokensAvailable() external view returns (uint256) { return OWNER_SUPPLY.sub(OWNER_SENT); } function bountyTokensSent() external view returns (uint256) { return BOUNTY_SENT; } function bountyTokensAvailable() external view returns (uint256) { return BOUNTY_SUPPLY.sub(BOUNTY_SENT); } function advisorsTokensSent() external view returns (uint256) { return ADVISORS_SENT; } function advisorsTokensAvailable() external view returns (uint256) { return ADVISORS_SUPPLY.sub(ADVISORS_SENT); } /** * @dev Transfer tokens from msg.sender account directy to address array with values array. * param _dests recipients. * @param _values Tokens values. */ function transferArray(address[] _dests, uint256[] _values) public returns (bool success) { require(_dests.length == _values.length); for (uint32 i = 0; i < _dests.length; i++) { if(_values[i] > balances[msg.sender] || msg.sender == _dests[i] || _dests[i] == address(0)) { revert(); return false; } balances[msg.sender] = balances[msg.sender].sub(_values[i]); balances[_dests[i]] = balances[_dests[i]].add(_values[i]); emit Transfer(msg.sender, _dests[i], _values[i]); } return true; } }
Reclaim all ERC20Basic compatible tokens _token ERC20Basic The address of the token contract/
function reclaimToken(ERC20Basic _token) external onlyAdmin { uint256 balance = _token.balanceOf(this); _token.safeTransfer(msg.sender, balance); }
15,798,331
pragma solidity 0.5.12; /** * (c) 2021 Akiva Capital Holdings, LLC. All Rights Reserved. * * For LICENSE details, please visit: * https://github.com/akiva-capital-holdings/pairwyse-smart-contracts/blob/master/LICENSE * */ import "../helpers/ClaimableBase.sol"; import "../helpers/RaySupport.sol"; /** * @title Config for Agreement contract */ contract Config is ClaimableBase, RaySupport { mapping(bytes32 => bool) public collateralsEnabled; mapping(bytes32 => uint) private minCollateralAmount; // collateralType => minCollateralAmount mapping(bytes32 => uint) private maxCollateralAmount; // collateralType => maxCollateralAmount // max duration in secs available for approve after creation, if expires - agreementshould be closed uint public approveLimit; // max duration in secs available for match after approve, if expires - agreement should be closed uint public matchLimit; uint public injectionThreshold; uint public minDuration; uint public maxDuration; uint public riskyMargin; uint public acapFee; // per second % address payable public acapAddr; /** * @dev Set default config */ constructor() public { // last parameter: fee is 0.5% annual in per-second compounding setGeneral(7 days, 1 days, 0.01 ether, 1 minutes, 1000 days, 20); setCollateral("ETH-A", true); setCollateral("BAT-A", true); setCollateral("WBTC-A", true); setCollateral("USDC-A", true); setCollateral("USDC-B", true); setCollateral("UNIV2USDCETH-A", true); acapFee = 1000000000158153903837946257; acapAddr = 0xF79179D06C687342a3f5C1daE5A7253AFC03C7A8; } /** * @dev Set all config parameters * @param _approveLimit max time available for approve after creation, if expires - agreement should be closed * @param _matchLimit max time available for match after approve, if expires - agreement should be closed * @param _injectionThreshold minimal threshold permitted for injection * @param _minDuration min agreement length * @param _maxDuration max agreement length * @param _riskyMargin risky Margin % */ function setGeneral( uint _approveLimit, uint _matchLimit, uint _injectionThreshold, uint _minDuration, uint _maxDuration, uint _riskyMargin ) public onlyContractOwner { approveLimit = _approveLimit; matchLimit = _matchLimit; injectionThreshold = _injectionThreshold; minDuration = _minDuration; maxDuration = _maxDuration; riskyMargin = _riskyMargin; } function checkCollateralAmount(bytes32 collateralType, uint amount) public view returns (bool) { return minCollateralAmount[collateralType] < amount && amount < getMaxCollateralAmount(collateralType); } function setMinCollateralAmount(bytes32[] memory collateralTypes, uint[] memory amounts) public onlyContractOwner { require(collateralTypes.length == amounts.length, "CNF1"); for (uint i = 0; i < collateralTypes.length; i++) { minCollateralAmount[collateralTypes[i]] = amounts[i]; } } function getMaxCollateralAmount(bytes32 collateralType) public view returns (uint) { assert(maxCollateralAmount[collateralType] != 0); return maxCollateralAmount[collateralType]; } function setMaxCollateralAmount(bytes32[] memory collateralTypes, uint[] memory amounts) public onlyContractOwner { require(collateralTypes.length == amounts.length, "CNF1"); for (uint i = 0; i < collateralTypes.length; i++) { maxCollateralAmount[collateralTypes[i]] = amounts[i]; } } /** * @dev Set config parameter * @param _acapFee fee in % per second */ function setAcapFee(uint _acapFee) public onlyContractOwner { acapFee = _acapFee; } /** * @dev Set config parameter * @param _a address for fees */ function setAcapAddr(address payable _a) public onlyContractOwner { require(_a != address(0), "CNF2"); acapAddr = _a; } /** * @dev Set config parameter * @param _riskyMargin risky Margin % */ function setRiskyMargin(uint _riskyMargin) public onlyContractOwner { riskyMargin = _riskyMargin; } /** * @dev Set config parameter * @param _approveLimit max duration available for approve after creation, if expires - agreement should be closed */ function setApproveLimit(uint _approveLimit) public onlyContractOwner { approveLimit = _approveLimit; } /** * @dev Set config parameter * @param _matchLimit max duration available for match after approve, if expires - agreement should be closed */ function setMatchLimit(uint _matchLimit) public onlyContractOwner { matchLimit = _matchLimit; } /** * @dev Set config parameter * @param _injectionThreshold minimal threshold permitted for injection */ function setInjectionThreshold(uint _injectionThreshold) public onlyContractOwner { injectionThreshold = _injectionThreshold; } /** * @dev Set a collateral type * @param _ilk collateral type * @param _status collateral status (true/false) */ function setCollateral(bytes32 _ilk, bool _status) public onlyContractOwner { collateralsEnabled[_ilk] = _status; } function checkDuration(uint _duration) public view returns(bool) { return minDuration < _duration && _duration < maxDuration; } }
Set config parameter _riskyMargin risky Margin %/
function setRiskyMargin(uint _riskyMargin) public onlyContractOwner { riskyMargin = _riskyMargin; }
5,350,587
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@manifoldxyz/libraries-solidity/contracts/access/IAdminControl.sol"; import "@manifoldxyz/creator-core-solidity/contracts/core/IERC721CreatorCore.sol"; import "@manifoldxyz/creator-core-solidity/contracts/extensions/CreatorExtension.sol"; import "@manifoldxyz/creator-core-solidity/contracts/extensions/ICreatorExtensionTokenURI.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./IManifoldERC721Edition.sol"; /** * Manifold ERC721 Edition Controller Implementation */ contract ManifoldERC721Edition is CreatorExtension, ICreatorExtensionTokenURI, IManifoldERC721Edition, ReentrancyGuard { using Strings for uint256; struct IndexRange { uint256 startIndex; uint256 count; } mapping(address => mapping(uint256 => string)) _tokenPrefix; mapping(address => mapping(uint256 => uint256)) _maxSupply; mapping(address => mapping(uint256 => uint256)) _totalSupply; mapping(address => mapping(uint256 => IndexRange[])) _indexRanges; mapping(address => uint256) _currentSeries; /** * @dev Only allows approved admins to call the specified function */ modifier creatorAdminRequired(address creator) { require(IAdminControl(creator).isAdmin(msg.sender), "Must be owner or admin of creator contract"); _; } function supportsInterface(bytes4 interfaceId) public view virtual override(CreatorExtension, IERC165) returns (bool) { return interfaceId == type(ICreatorExtensionTokenURI).interfaceId || interfaceId == type(IManifoldERC721Edition).interfaceId || CreatorExtension.supportsInterface(interfaceId); } /** * @dev See {IManifoldERC721Edition-totalSupply}. */ function totalSupply(address creator, uint256 series) external view override returns(uint256) { return _totalSupply[creator][series]; } /** * @dev See {IManifoldERC721Edition-maxSupply}. */ function maxSupply(address creator, uint256 series) external view override returns(uint256) { return _maxSupply[creator][series]; } /** * @dev See {IManifoldERC721Edition-createSeries}. */ function createSeries(address creator, uint256 maxSupply_, string calldata prefix) external override creatorAdminRequired(creator) returns(uint256) { _currentSeries[creator] += 1; uint256 series = _currentSeries[creator]; _maxSupply[creator][series] = maxSupply_; _tokenPrefix[creator][series] = prefix; emit SeriesCreated(msg.sender, creator, series, maxSupply_); return series; } /** * @dev See {IManifoldERC721Edition-latestSeries}. */ function latestSeries(address creator) external view override returns(uint256) { return _currentSeries[creator]; } /** * See {IManifoldERC721Edition-setTokenURIPrefix}. */ function setTokenURIPrefix(address creator, uint256 series, string calldata prefix) external override creatorAdminRequired(creator) { require(series > 0 && series <= _currentSeries[creator], "Invalid series"); _tokenPrefix[creator][series] = prefix; } /** * @dev See {ICreatorExtensionTokenURI-tokenURI}. */ function tokenURI(address creator, uint256 tokenId) external view override returns (string memory) { (uint256 series, uint256 index) = _tokenSeriesAndIndex(creator, tokenId); return string(abi.encodePacked(_tokenPrefix[creator][series], (index+1).toString())); } /** * @dev See {IManifoldERC721Edition-mint}. */ function mint(address creator, uint256 series, address recipient, uint16 count) external override nonReentrant creatorAdminRequired(creator) { require(count > 0, "Invalid amount requested"); require(_totalSupply[creator][series]+count <= _maxSupply[creator][series], "Too many requested"); uint256[] memory tokenIds = IERC721CreatorCore(creator).mintExtensionBatch(recipient, count); _updateIndexRanges(creator, series, tokenIds[0], count); } /** * @dev See {IManifoldERC721Edition-mint}. */ function mint(address creator, uint256 series, address[] calldata recipients) external override nonReentrant creatorAdminRequired(creator) { require(recipients.length > 0, "Invalid amount requested"); require(_totalSupply[creator][series]+recipients.length <= _maxSupply[creator][series], "Too many requested"); uint256 startIndex = IERC721CreatorCore(creator).mintExtension(recipients[0]); for (uint256 i = 1; i < recipients.length; i++) { IERC721CreatorCore(creator).mintExtension(recipients[i]); } _updateIndexRanges(creator, series, startIndex, recipients.length); } /** * @dev Update the index ranges, which is used to figure out the index from a tokenId */ function _updateIndexRanges(address creator, uint256 series, uint256 startIndex, uint256 count) internal { IndexRange[] storage indexRanges = _indexRanges[creator][series]; if (indexRanges.length == 0) { indexRanges.push(IndexRange(startIndex, count)); } else { IndexRange storage lastIndexRange = indexRanges[indexRanges.length-1]; if ((lastIndexRange.startIndex + lastIndexRange.count) == startIndex) { lastIndexRange.count += count; } else { indexRanges.push(IndexRange(startIndex, count)); } } _totalSupply[creator][series] += count; } /** * @dev Index from tokenId */ function _tokenSeriesAndIndex(address creator, uint256 tokenId) internal view returns(uint256, uint256) { require(_currentSeries[creator] > 0, "Invalid token"); for (uint series=1; series <= _currentSeries[creator]; series++) { IndexRange[] memory indexRanges = _indexRanges[creator][series]; uint256 offset; for (uint i = 0; i < indexRanges.length; i++) { IndexRange memory currentIndex = indexRanges[i]; if (tokenId < currentIndex.startIndex) break; if (tokenId >= currentIndex.startIndex && tokenId < currentIndex.startIndex + currentIndex.count) { return (series, tokenId - currentIndex.startIndex + offset); } offset += currentIndex.count; } } revert("Invalid token"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Interface for admin control */ interface IAdminControl is IERC165 { event AdminApproved(address indexed account, address indexed sender); event AdminRevoked(address indexed account, address indexed sender); /** * @dev gets address of all admins */ function getAdmins() external view returns (address[] memory); /** * @dev add an admin. Can only be called by contract owner. */ function approveAdmin(address admin) external; /** * @dev remove an admin. Can only be called by contract owner. */ function revokeAdmin(address admin) external; /** * @dev checks whether or not given address is an admin * Returns True if they are */ function isAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "./ICreatorCore.sol"; /** * @dev Core ERC721 creator interface */ interface IERC721CreatorCore is ICreatorCore { /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to) external returns (uint256); /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to) external returns (uint256); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenIds minted */ function mintExtensionBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtensionBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev burn a token. Can only be called by token owner or approved address. * On burn, calls back to the registered extension's onBurn method */ function burn(uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @dev Base creator extension variables */ abstract contract CreatorExtension is ERC165 { /** * @dev Legacy extension interface identifiers * * {IERC165-supportsInterface} needs to return 'true' for this interface * in order backwards compatible with older creator contracts */ bytes4 constant internal LEGACY_EXTENSION_INTERFACE = 0x7005caad; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) { return interfaceId == LEGACY_EXTENSION_INTERFACE || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Implement this if you want your extension to have overloadable URI's */ interface ICreatorExtensionTokenURI is IERC165 { /** * Get the uri for a given creator/tokenId */ function tokenURI(address creator, uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz /** * Manifold ERC721 Edition Controller interface */ interface IManifoldERC721Edition { event SeriesCreated(address caller, address creator, uint256 series, uint256 maxSupply); /** * @dev Create a new series. Returns the series id. */ function createSeries(address creator, uint256 maxSupply, string calldata prefix) external returns(uint256); /** * @dev Get the latest series created. */ function latestSeries(address creator) external view returns(uint256); /** * @dev Set the token uri prefix */ function setTokenURIPrefix(address creator, uint256 series, string calldata prefix) external; /** * @dev Mint NFTs to a single recipient */ function mint(address creator, uint256 series, address recipient, uint16 count) external; /** * @dev Mint NFTS to the recipients */ function mint(address creator, uint256 series, address[] calldata recipients) external; /** * @dev Total supply of editions */ function totalSupply(address creator, uint256 series) external view returns(uint256); /** * @dev Max supply of editions */ function maxSupply(address creator, uint256 series) external view returns(uint256); } // 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 pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Core creator interface */ interface ICreatorCore is IERC165 { event ExtensionRegistered(address indexed extension, address indexed sender); event ExtensionUnregistered(address indexed extension, address indexed sender); event ExtensionBlacklisted(address indexed extension, address indexed sender); event MintPermissionsUpdated(address indexed extension, address indexed permissions, address indexed sender); event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints); event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints); event ExtensionRoyaltiesUpdated(address indexed extension, address payable[] receivers, uint256[] basisPoints); event ExtensionApproveTransferUpdated(address indexed extension, bool enabled); /** * @dev gets address of all extensions */ function getExtensions() external view returns (address[] memory); /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI) external; /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external; /** * @dev add an extension. Can only be called by contract owner or admin. * Returns True if removed, False if already removed. */ function unregisterExtension(address extension) external; /** * @dev blacklist an extension. Can only be called by contract owner or admin. * This function will destroy all ability to reference the metadata of any tokens created * by the specified extension. It will also unregister the extension if needed. * Returns True if removed, False if already removed. */ function blacklistExtension(address extension) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. */ function setBaseTokenURIExtension(string calldata uri) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURIExtension(string calldata uri, bool identical) external; /** * @dev set the common prefix of an extension. Can only be called by extension. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefixExtension(string calldata prefix) external; /** * @dev set the tokenURI of a token extension. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256[] memory tokenId, string[] calldata uri) external; /** * @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURI(string calldata uri) external; /** * @dev set the common prefix for tokens with no extension. Can only be called by owner/admin. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefix(string calldata prefix) external; /** * @dev set the tokenURI of a token with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external; /** * @dev set a permissions contract for an extension. Used to control minting. */ function setMintPermissions(address extension, address permissions) external; /** * @dev Configure so transfers of tokens created by the caller (must be extension) gets approval * from the extension before transferring */ function setApproveTransferExtension(bool enabled) external; /** * @dev get the extension of a given token */ function tokenExtension(uint256 tokenId) external view returns (address); /** * @dev Set default royalties */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of a token */ function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of an extension */ function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Get royalites of a token. Returns list of receivers and basisPoints */ function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); // Royalty support for various other standards function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); function getFeeBps(uint256 tokenId) external view returns (uint[] memory); function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function royaltyInfo(uint256 tokenId, uint256 value) external view returns (address, uint256); } // 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; } }
See {IManifoldERC721Edition-mint}./
function mint(address creator, uint256 series, address recipient, uint16 count) external override nonReentrant creatorAdminRequired(creator) { require(count > 0, "Invalid amount requested"); require(_totalSupply[creator][series]+count <= _maxSupply[creator][series], "Too many requested"); uint256[] memory tokenIds = IERC721CreatorCore(creator).mintExtensionBatch(recipient, count); _updateIndexRanges(creator, series, tokenIds[0], count); }
6,155,510
pragma solidity ^0.4.24; import "./Moduler.sol"; import "./ReliableToken.sol"; /** * @title TokenDrop * @dev TokenDrop is a token holder contract that will spread * locked tokens multiply */ contract TokenDrop is Moduler { /** * @dev Creates a contract that drop its initication balances of locked ERC20 token for gift * @param _token token of ERC20 token which is being managed */ constructor(ReliableToken _token) public Moduler(_token) { } /** * @dev Transfers tokens held by timelock to recipients multiply. * @param _toList address of the recipients to whom received tokens * @param _lockAmountEach uint256 the amount of tokens to be transferred * #param _expiresAtList release times */ function spreadConditional( address[] _toList, uint256 _valueEach, uint256 _lockAmountEach, uint256[] _expiresAtList ) public onlyOwner returns (bool) { require(_toList.length > 0); require(_valueEach.mul(_toList.length) <= token.balanceOf(this)); require(hasTokenOwnership()); for (uint i = 0; i < _toList.length; i++ ) { token.transferLocked(_toList[i], _valueEach, _lockAmountEach, _expiresAtList); } return true; } /** * @dev Transfers tokens to recipients multiply. * @param _toList address of the recipients to whom received tokens * @param _amountEach uint256 the amount of tokens to be transferred */ function spread( address[] _toList, uint256 _amountEach ) public returns (bool) { require(_toList.length > 0); require(_amountEach.mul(_toList.length) <= token.balanceOf(this)); for (uint i = 0; i < _toList.length; i++ ) { token.transfer(_toList[i], _amountEach); } return true; } /** * @dev Validate spread without condition. */ function spreadValidation( address[] _toList, uint256 _amountEach ) public view returns (bool) { return _toList.length > 0 && _amountEach.mul(_toList.length) <= token.balanceOf(this); } /** * @dev Validate spread with condition. */ function spreadConditionalValidation( address[] _toList, uint256 _amountEach ) public view returns (bool) { return spreadValidation(_toList, _amountEach) && hasTokenOwnership(); } }
Validate spread with condition./
function spreadConditionalValidation( address[] _toList, uint256 _amountEach ) public view returns (bool) { return spreadValidation(_toList, _amountEach) && hasTokenOwnership(); }
6,415,842
./full_match/137/0xeFeDd0Cb8D5AACA047af0Bf4E89a5a5826B6fe38/sources/MasterChef.sol
View function to see pending TUNDRAs on frontend.
function pendingTUNDRA(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTUNDRAPerShare = pool.accTUNDRAPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 TUNDRAReward = multiplier.mul(TUNDRAPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); accTUNDRAPerShare = accTUNDRAPerShare.add( TUNDRAReward.mul(1e18).div(lpSupply) ); } return user.amount.mul(accTUNDRAPerShare).div(1e18).sub(user.rewardDebt); }
4,724,609
/** * Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; import "./AdvancedToken.sol"; import "./interfaces/ProtocolLike.sol"; import "./interfaces/FeedsLike.sol"; contract LoanTokenLogicStandard is AdvancedToken { using SafeMath for uint256; using SignedSafeMath for int256; // It is important to maintain the variables order so the delegate calls can access sovrynContractAddress and wrbtcTokenAddress address public sovrynContractAddress; address public wrbtcTokenAddress; address internal target_; uint256 public constant VERSION = 5; address internal constant arbitraryCaller = 0x000F400e6818158D541C3EBE45FE3AA0d47372FF; function() external { revert("loan token logic - fallback not allowed"); } /* Public functions */ function mint( address receiver, uint256 depositAmount) external nonReentrant returns (uint256 mintAmount) { //temporary: limit transaction size if(transactionLimit[loanTokenAddress] > 0) require(depositAmount <= transactionLimit[loanTokenAddress]); return _mintToken( receiver, depositAmount ); } function burn( address receiver, uint256 burnAmount) external nonReentrant returns (uint256 loanAmountPaid) { loanAmountPaid = _burnToken( burnAmount ); if (loanAmountPaid != 0) { _safeTransfer(loanTokenAddress, receiver, loanAmountPaid, "5"); } } /* flashBorrow is disabled for the MVP, but is going to be added later. therefore, it needs to be revised function flashBorrow( uint256 borrowAmount, address borrower, address target, string calldata signature, bytes calldata data) external payable nonReentrant pausable(msg.sig) settlesInterest returns (bytes memory) { require(borrowAmount != 0, "38"); _checkPause(); _settleInterest(); // save before balances uint256 beforeEtherBalance = address(this).balance.sub(msg.value); uint256 beforeAssetsBalance = _underlyingBalance() .add(totalAssetBorrow()); // lock totalAssetSupply for duration of flash loan _flTotalAssetSupply = beforeAssetsBalance; // transfer assets to calling contract _safeTransfer(loanTokenAddress, borrower, borrowAmount, "39"); bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // arbitrary call (bool success, bytes memory returnData) = arbitraryCaller.call.value(msg.value)( abi.encodeWithSelector( 0xde064e0d, // sendCall(address,bytes) target, callData ) ); require(success, "call failed"); // unlock totalAssetSupply _flTotalAssetSupply = 0; // verifies return of flash loan require( address(this).balance >= beforeEtherBalance && _underlyingBalance() .add(totalAssetBorrow()) >= beforeAssetsBalance, "40" ); return returnData; } */ /** * borrows funds from the pool. The underlying loan token may not be used as collateral. * @param loanId the ID of the loan, 0 for a new loan * @param withdrawAmount the amount to be withdrawn (actually borrowed) * @param initialLoanDuration the duration of the loan in seconds. if the loan is not paid back until then, it'll need to be rolled over * @param collateralTokenSent the amount of collateral token sent (150% of the withdrawn amount worth in collateral tokenns) * @param collateralTokenAddress the address of the tokenn to be used as collateral. cannot be the loan token address * @param borrower the one paying for the collateral * @param receiver the one receiving the withdrawn amount * */ function borrow( bytes32 loanId, // 0 if new loan uint256 withdrawAmount, uint256 initialLoanDuration, // duration in seconds uint256 collateralTokenSent, // if 0, loanId must be provided; any ETH sent must equal this value address collateralTokenAddress, // if address(0), this means ETH and ETH must be sent with the call or loanId must be provided address borrower, address receiver, bytes memory /*loanDataBytes*/) // arbitrary order data (for future use) public payable nonReentrant //note: needs to be removed to allow flashloan use cases returns (uint256, uint256) // returns new principal and new collateral added to loan { require(withdrawAmount != 0, "6"); _checkPause(); //temporary: limit transaction size if(transactionLimit[collateralTokenAddress] > 0) require(collateralTokenSent <= transactionLimit[collateralTokenAddress]); require(msg.value == 0 || msg.value == collateralTokenSent, "7"); require(collateralTokenSent != 0 || loanId != 0, "8"); require(collateralTokenAddress != address(0) || msg.value != 0 || loanId != 0, "9"); if (collateralTokenAddress == address(0)) { collateralTokenAddress = wrbtcTokenAddress; } require(collateralTokenAddress != loanTokenAddress, "10"); _settleInterest(); address[4] memory sentAddresses; uint256[5] memory sentAmounts; sentAddresses[0] = address(this); // lender sentAddresses[1] = borrower; sentAddresses[2] = receiver; //sentAddresses[3] = address(0); // manager sentAmounts[1] = withdrawAmount; // interestRate, interestInitialAmount, borrowAmount (newBorrowAmount) (sentAmounts[0], sentAmounts[2], sentAmounts[1]) = _getInterestRateAndBorrowAmount( sentAmounts[1], _totalAssetSupply(0), // interest is settled above initialLoanDuration ); //sentAmounts[3] = 0; // loanTokenSent sentAmounts[4] = collateralTokenSent; return _borrowOrTrade( loanId, withdrawAmount, 2 * 10**18, // leverageAmount (translates to 150% margin for a Torque loan) collateralTokenAddress, sentAddresses, sentAmounts, "" // loanDataBytes ); } // Called to borrow and immediately get into a positions function marginTrade( bytes32 loanId, // 0 if new loan uint256 leverageAmount, // expected in x * 10**18 where x is the actual leverage (2, 3, 4, or 5) uint256 loanTokenSent, uint256 collateralTokenSent, address collateralTokenAddress, address trader, bytes memory loanDataBytes) // arbitrary order data public payable nonReentrant //note: needs to be removed to allow flashloan use cases returns (uint256, uint256) // returns new principal and new collateral added to trade { _checkPause(); if (collateralTokenAddress == address(0)) { collateralTokenAddress = wrbtcTokenAddress; } require(collateralTokenAddress != loanTokenAddress, "11"); //temporary: limit transaction size if(transactionLimit[collateralTokenAddress] > 0) require(collateralTokenSent <= transactionLimit[collateralTokenAddress]); if(transactionLimit[loanTokenAddress] > 0) require(loanTokenSent <= transactionLimit[loanTokenAddress]); //computes the worth of the total deposit in loan tokens. //(loanTokenSent + convert(collateralTokenSent)) //no actual swap happening here. uint256 totalDeposit = _totalDeposit( collateralTokenAddress, collateralTokenSent, loanTokenSent ); require(totalDeposit != 0, "12"); address[4] memory sentAddresses; uint256[5] memory sentAmounts; sentAddresses[0] = address(this); // lender sentAddresses[1] = trader; sentAddresses[2] = trader; //sentAddresses[3] = address(0); // manager //sentAmounts[0] = 0; // interestRate (found later) sentAmounts[1] = totalDeposit; // total amount of deposit //sentAmounts[2] = 0; // interestInitialAmount (interest is calculated based on fixed-term loan) sentAmounts[3] = loanTokenSent; sentAmounts[4] = collateralTokenSent; _settleInterest(); (sentAmounts[1], sentAmounts[0]) = _getMarginBorrowAmountAndRate( // borrowAmount, interestRate leverageAmount, sentAmounts[1] // depositAmount ); return _borrowOrTrade( loanId, 0, // withdrawAmount leverageAmount, collateralTokenAddress, sentAddresses, sentAmounts, loanDataBytes ); } function transfer( address _to, uint256 _value) external returns (bool) { return _internalTransferFrom( msg.sender, _to, _value, uint256(-1) ); } function transferFrom( address _from, address _to, uint256 _value) external returns (bool) { return _internalTransferFrom( _from, _to, _value, ProtocolLike(sovrynContractAddress).isLoanPool(msg.sender) ? uint256(-1) : allowed[_from][msg.sender] ); } function _internalTransferFrom( address _from, address _to, uint256 _value, uint256 _allowanceAmount) internal returns (bool) { if (_allowanceAmount != uint256(-1)) { require(_value <= _allowanceAmount, "14"); allowed[_from][msg.sender] = _allowanceAmount.sub(_value); } uint256 _balancesFrom = balances[_from]; require(_value <= _balancesFrom && _to != address(0), "14" ); uint256 _balancesFromNew = _balancesFrom .sub(_value); balances[_from] = _balancesFromNew; uint256 _balancesTo = balances[_to]; uint256 _balancesToNew = _balancesTo .add(_value); balances[_to] = _balancesToNew; // handle checkpoint update uint256 _currentPrice = tokenPrice(); _updateCheckpoints( _from, _balancesFrom, _balancesFromNew, _currentPrice ); _updateCheckpoints( _to, _balancesTo, _balancesToNew, _currentPrice ); emit Transfer(_from, _to, _value); return true; } event Debug( bytes32 slot, uint256 one, uint256 two ); /** * @dev updates the user's checkpoint price and profit so far. * @param _user the user address * @param _oldBalance the user's previous balance * @param _newBalance the user's updated balance * @param _currentPrice the current iToken price * */ function _updateCheckpoints( address _user, uint256 _oldBalance, uint256 _newBalance, uint256 _currentPrice) internal { // keccak256("iToken_ProfitSoFar") bytes32 slot = keccak256( abi.encodePacked(_user, uint256(0x37aa2b7d583612f016e4a4de4292cb015139b3d7762663d06a53964912ea2fb6)) ); uint256 _currentProfit; if (_oldBalance != 0 && _newBalance != 0) { _currentProfit = _profitOf( slot, _oldBalance, _currentPrice, checkpointPrices_[_user] ); } else if (_newBalance == 0) { _currentPrice = 0; } assembly { sstore(slot, _currentProfit) } checkpointPrices_[_user] = _currentPrice; emit Debug( slot, _currentProfit, _currentPrice ); } /* Public View functions */ function profitOf( address user) public view returns (uint256) { // keccak256("iToken_ProfitSoFar") bytes32 slot = keccak256( abi.encodePacked(user, uint256(0x37aa2b7d583612f016e4a4de4292cb015139b3d7762663d06a53964912ea2fb6)) ); return _profitOf( slot, balances[user], tokenPrice(), checkpointPrices_[user] ); } function _profitOf( bytes32 slot, uint256 _balance, uint256 _currentPrice, uint256 _checkpointPrice) internal view returns (uint256) { if (_checkpointPrice == 0) { return 0; } uint256 profitSoFar; uint256 profitDiff; assembly { profitSoFar := sload(slot) } if (_currentPrice > _checkpointPrice) { profitDiff = _balance .mul(_currentPrice - _checkpointPrice) .div(10**18); profitSoFar = profitSoFar .add(profitDiff); } else { profitDiff = _balance .mul(_checkpointPrice - _currentPrice) .div(10**18); if (profitSoFar > profitDiff) { profitSoFar = profitSoFar - profitDiff; } else { profitSoFar = 0; } } return profitSoFar; } function tokenPrice() public view returns (uint256 price) { uint256 interestUnPaid; if (lastSettleTime_ != uint88(block.timestamp)) { (,interestUnPaid) = _getAllInterest(); } return _tokenPrice(_totalAssetSupply(interestUnPaid)); } function checkpointPrice( address _user) public view returns (uint256 price) { return checkpointPrices_[_user]; } function marketLiquidity() public view returns (uint256) { uint256 totalSupply = _totalAssetSupply(0); uint256 totalBorrow = totalAssetBorrow(); if (totalSupply > totalBorrow) { return totalSupply.sub(totalBorrow); } } function avgBorrowInterestRate() public view returns (uint256) { return _avgBorrowInterestRate(totalAssetBorrow()); } // the minimum rate the next base protocol borrower will receive for variable-rate loans function borrowInterestRate() public view returns (uint256) { return _nextBorrowInterestRate(0); } function nextBorrowInterestRate( uint256 borrowAmount) public view returns (uint256) { return _nextBorrowInterestRate(borrowAmount); } // interest that lenders are currently receiving when supplying to the pool function supplyInterestRate() public view returns (uint256) { return totalSupplyInterestRate(_totalAssetSupply(0)); } function nextSupplyInterestRate( uint256 supplyAmount) public view returns (uint256) { return totalSupplyInterestRate(_totalAssetSupply(0).add(supplyAmount)); } function totalSupplyInterestRate( uint256 assetSupply) public view returns (uint256) { uint256 assetBorrow = totalAssetBorrow(); if (assetBorrow != 0) { return _supplyInterestRate( assetBorrow, assetSupply ); } } function totalAssetBorrow() public view returns (uint256) { return ProtocolLike(sovrynContractAddress).getTotalPrincipal( address(this), loanTokenAddress ); } function totalAssetSupply() public view returns (uint256) { uint256 interestUnPaid; if (lastSettleTime_ != uint88(block.timestamp)) { (,interestUnPaid) = _getAllInterest(); } return _totalAssetSupply(interestUnPaid); } function getMaxEscrowAmount( uint256 leverageAmount) public view returns (uint256) { uint256 initialMargin = SafeMath.div(10**38, leverageAmount); return marketLiquidity() .mul(initialMargin) .div(_adjustValue( 10**20, // maximum possible interest (100%) 2419200, // 28 day duration for margin trades initialMargin)); } // returns the user's balance of underlying token function assetBalanceOf( address _owner) public view returns (uint256) { return balanceOf(_owner) .mul(tokenPrice()) .div(10**18); } function getEstimatedMarginDetails( uint256 leverageAmount, uint256 loanTokenSent, uint256 collateralTokenSent, address collateralTokenAddress) // address(0) means ETH public view returns (uint256 principal, uint256 collateral, uint256 interestRate) { if (collateralTokenAddress == address(0)) { collateralTokenAddress = wrbtcTokenAddress; } uint256 totalDeposit = _totalDeposit( collateralTokenAddress, collateralTokenSent, loanTokenSent ); (principal, interestRate) = _getMarginBorrowAmountAndRate( leverageAmount, totalDeposit ); if (principal > _underlyingBalance()) { return (0, 0, 0); } loanTokenSent = loanTokenSent .add(principal); collateral = ProtocolLike(sovrynContractAddress).getEstimatedMarginExposure( loanTokenAddress, collateralTokenAddress, loanTokenSent, collateralTokenSent, interestRate, principal ); } function getDepositAmountForBorrow( uint256 borrowAmount, uint256 initialLoanDuration, // duration in seconds address collateralTokenAddress) // address(0) means ETH public view returns (uint256 depositAmount) { if (borrowAmount != 0) { (,,uint256 newBorrowAmount) = _getInterestRateAndBorrowAmount( borrowAmount, totalAssetSupply(), initialLoanDuration ); if (newBorrowAmount <= _underlyingBalance()) { return ProtocolLike(sovrynContractAddress).getRequiredCollateral( loanTokenAddress, collateralTokenAddress != address(0) ? collateralTokenAddress : wrbtcTokenAddress, newBorrowAmount, 50 * 10**18, // initialMargin true // isTorqueLoan ).add(10); // some dust to compensate for rounding errors } } } function getBorrowAmountForDeposit( uint256 depositAmount, uint256 initialLoanDuration, // duration in seconds address collateralTokenAddress) // address(0) means ETH public view returns (uint256 borrowAmount) { if (depositAmount != 0) { borrowAmount = ProtocolLike(sovrynContractAddress).getBorrowAmount( loanTokenAddress, collateralTokenAddress != address(0) ? collateralTokenAddress : wrbtcTokenAddress, depositAmount, 50 * 10**18, // initialMargin, true // isTorqueLoan ); (,,borrowAmount) = _getInterestRateAndBorrowAmount( borrowAmount, totalAssetSupply(), initialLoanDuration ); if (borrowAmount > _underlyingBalance()) { borrowAmount = 0; } } } /* Internal functions */ function _mintToken( address receiver, uint256 depositAmount) internal returns (uint256 mintAmount) { require (depositAmount != 0, "17"); _settleInterest(); uint256 currentPrice = _tokenPrice(_totalAssetSupply(0)); mintAmount = depositAmount .mul(10**18) .div(currentPrice); if (msg.value == 0) { _safeTransferFrom(loanTokenAddress, msg.sender, address(this), depositAmount, "18"); } else { IWrbtc(wrbtcTokenAddress).deposit.value(depositAmount)(); } uint256 oldBalance = balances[receiver]; _updateCheckpoints( receiver, oldBalance, _mint(receiver, mintAmount, depositAmount, currentPrice), // newBalance currentPrice ); } function _burnToken( uint256 burnAmount) internal returns (uint256 loanAmountPaid) { require(burnAmount != 0, "19"); if (burnAmount > balanceOf(msg.sender)) { burnAmount = balanceOf(msg.sender); } _settleInterest(); uint256 currentPrice = _tokenPrice(_totalAssetSupply(0)); uint256 loanAmountOwed = burnAmount .mul(currentPrice) .div(10**18); uint256 loanAmountAvailableInContract = _underlyingBalance(); loanAmountPaid = loanAmountOwed; require(loanAmountPaid <= loanAmountAvailableInContract, "37"); uint256 oldBalance = balances[msg.sender]; //this function does not only update the checkpoints but also the current profit of the user _updateCheckpoints( msg.sender, oldBalance, _burn(msg.sender, burnAmount, loanAmountPaid, currentPrice), // newBalance currentPrice ); } function _settleInterest() internal { uint88 ts = uint88(block.timestamp); if (lastSettleTime_ != ts) { ProtocolLike(sovrynContractAddress).withdrawAccruedInterest( loanTokenAddress ); lastSettleTime_ = ts; } } function _totalDeposit( address collateralTokenAddress, uint256 collateralTokenSent, uint256 loanTokenSent) internal view returns (uint256 totalDeposit) { totalDeposit = loanTokenSent; if (collateralTokenSent != 0) { (uint256 sourceToDestRate, uint256 sourceToDestPrecision) = FeedsLike(ProtocolLike(sovrynContractAddress).priceFeeds()).queryRate( collateralTokenAddress, loanTokenAddress ); if (sourceToDestPrecision != 0) { totalDeposit = collateralTokenSent .mul(sourceToDestRate) .div(sourceToDestPrecision) .add(totalDeposit); } } } function _getInterestRateAndBorrowAmount( uint256 borrowAmount, uint256 assetSupply, uint256 initialLoanDuration) // duration in seconds internal view returns (uint256 interestRate, uint256 interestInitialAmount, uint256 newBorrowAmount) { interestRate = _nextBorrowInterestRate2( borrowAmount, assetSupply ); // newBorrowAmount = borrowAmount * 10^18 / (10^18 - interestRate * 7884000 * 10^18 / 31536000 / 10^20) newBorrowAmount = borrowAmount .mul(10**18) .div( SafeMath.sub(10**18, interestRate .mul(initialLoanDuration) .mul(10**18) .div(31536000 * 10**20) // 365 * 86400 * 10**20 ) ); interestInitialAmount = newBorrowAmount .sub(borrowAmount); } // returns newPrincipal function _borrowOrTrade( bytes32 loanId, uint256 withdrawAmount, uint256 leverageAmount, address collateralTokenAddress, address[4] memory sentAddresses, uint256[5] memory sentAmounts, bytes memory loanDataBytes) internal returns (uint256, uint256) { _checkPause(); require (sentAmounts[1] <= _underlyingBalance() && // newPrincipal (borrowed amount + fees) sentAddresses[1] != address(0), // borrower "24" ); if (sentAddresses[2] == address(0)) { sentAddresses[2] = sentAddresses[1]; // receiver = borrower } // handle transfers prior to adding newPrincipal to loanTokenSent uint256 msgValue = _verifyTransfers( collateralTokenAddress, sentAddresses, sentAmounts, withdrawAmount ); // adding the loan token portion from the lender to loanTokenSent // (add the loan to the loan tokens sent from the user) sentAmounts[3] = sentAmounts[3] .add(sentAmounts[1]); // newPrincipal if (withdrawAmount != 0) { // withdrawAmount already sent to the borrower, so we aren't sending it to the protocol sentAmounts[3] = sentAmounts[3] .sub(withdrawAmount); } bytes32 loanParamsId = loanParamsIds[uint256(keccak256(abi.encodePacked( collateralTokenAddress, withdrawAmount != 0 ? // isTorqueLoan true : false )))]; // converting to initialMargin leverageAmount = SafeMath.div(10**38, leverageAmount); (sentAmounts[1], sentAmounts[4]) = ProtocolLike(sovrynContractAddress).borrowOrTradeFromPool.value(msgValue)( // newPrincipal, newCollateral loanParamsId, loanId, withdrawAmount != 0 ? // isTorqueLoan true : false, leverageAmount, // initialMargin sentAddresses, sentAmounts, loanDataBytes ); require (sentAmounts[1] != 0, "25"); return (sentAmounts[1], sentAmounts[4]); // newPrincipal, newCollateral } // sentAddresses[0]: lender // sentAddresses[1]: borrower // sentAddresses[2]: receiver // sentAddresses[3]: manager // sentAmounts[0]: interestRate // sentAmounts[1]: newPrincipal // sentAmounts[2]: interestInitialAmount // sentAmounts[3]: loanTokenSent // sentAmounts[4]: collateralTokenSent function _verifyTransfers( address collateralTokenAddress, address[4] memory sentAddresses, uint256[5] memory sentAmounts, uint256 withdrawalAmount) internal returns (uint256 msgValue) { address _wrbtcToken = wrbtcTokenAddress; address _loanTokenAddress = loanTokenAddress; address receiver = sentAddresses[2]; uint256 newPrincipal = sentAmounts[1]; uint256 loanTokenSent = sentAmounts[3]; uint256 collateralTokenSent = sentAmounts[4]; require(_loanTokenAddress != collateralTokenAddress, "26"); msgValue = msg.value; if (withdrawalAmount != 0) { // withdrawOnOpen == true _safeTransfer(_loanTokenAddress, receiver, withdrawalAmount, ""); if (newPrincipal > withdrawalAmount) { _safeTransfer(_loanTokenAddress, sovrynContractAddress, newPrincipal - withdrawalAmount, ""); } } else { _safeTransfer(_loanTokenAddress, sovrynContractAddress, newPrincipal, "27"); } //this is a critical piece of code! //wEth are supposed to be held by the contract itself, while other tokens are being transfered from the sender directly if (collateralTokenSent != 0) { if (collateralTokenAddress == _wrbtcToken && msgValue != 0 && msgValue >= collateralTokenSent) { IWrbtc(_wrbtcToken).deposit.value(collateralTokenSent)(); _safeTransfer(collateralTokenAddress, sovrynContractAddress, collateralTokenSent, "28-a"); msgValue -= collateralTokenSent; } else { _safeTransferFrom(collateralTokenAddress, msg.sender, sovrynContractAddress, collateralTokenSent, "28-b"); } } if (loanTokenSent != 0) { _safeTransferFrom(_loanTokenAddress, msg.sender, sovrynContractAddress, loanTokenSent, "29"); } } function _safeTransfer( address token, address to, uint256 amount, string memory errorMsg) internal { _callOptionalReturn( token, abi.encodeWithSelector(IERC20(token).transfer.selector, to, amount), errorMsg ); } function _safeTransferFrom( address token, address from, address to, uint256 amount, string memory errorMsg) internal { _callOptionalReturn( token, abi.encodeWithSelector(IERC20(token).transferFrom.selector, from, to, amount), errorMsg ); } function _callOptionalReturn( address token, bytes memory data, string memory errorMsg) internal { (bool success, bytes memory returndata) = token.call(data); require(success, errorMsg); if (returndata.length != 0) { require(abi.decode(returndata, (bool)), errorMsg); } } function _underlyingBalance() internal view returns (uint256) { return IERC20(loanTokenAddress).balanceOf(address(this)); } /* Internal View functions */ function _tokenPrice( uint256 assetSupply) internal view returns (uint256) { uint256 totalTokenSupply = totalSupply_; return totalTokenSupply != 0 ? assetSupply .mul(10**18) .div(totalTokenSupply) : initialPrice; } function _avgBorrowInterestRate( uint256 assetBorrow) internal view returns (uint256) { if (assetBorrow != 0) { (uint256 interestOwedPerDay,) = _getAllInterest(); return interestOwedPerDay .mul(10**20) .div(assetBorrow) .mul(365); } } // next supply interest adjustment function _supplyInterestRate( uint256 assetBorrow, uint256 assetSupply) public view returns (uint256) { if (assetBorrow != 0 && assetSupply >= assetBorrow) { return _avgBorrowInterestRate(assetBorrow) .mul(_utilizationRate(assetBorrow, assetSupply)) .mul(SafeMath.sub(10**20, ProtocolLike(sovrynContractAddress).lendingFeePercent())) .div(10**40); } } function _nextBorrowInterestRate( uint256 borrowAmount) internal view returns (uint256) { uint256 interestUnPaid; if (borrowAmount != 0) { if (lastSettleTime_ != uint88(block.timestamp)) { (,interestUnPaid) = _getAllInterest(); } uint256 balance = _underlyingBalance() .add(interestUnPaid); if (borrowAmount > balance) { borrowAmount = balance; } } return _nextBorrowInterestRate2( borrowAmount, _totalAssetSupply(interestUnPaid) ); } function _nextBorrowInterestRate2( uint256 newBorrowAmount, uint256 assetSupply) internal view returns (uint256 nextRate) { uint256 utilRate = _utilizationRate( totalAssetBorrow().add(newBorrowAmount), assetSupply ); uint256 thisMinRate; uint256 thisMaxRate; uint256 thisBaseRate = baseRate; uint256 thisRateMultiplier = rateMultiplier; uint256 thisTargetLevel = targetLevel; uint256 thisKinkLevel = kinkLevel; uint256 thisMaxScaleRate = maxScaleRate; if (utilRate < thisTargetLevel) { // target targetLevel utilization when utilization is under targetLevel utilRate = thisTargetLevel; } if (utilRate > thisKinkLevel) { // scale rate proportionally up to 100% uint256 thisMaxRange = WEI_PERCENT_PRECISION - thisKinkLevel; // will not overflow utilRate -= thisKinkLevel; if (utilRate > thisMaxRange) utilRate = thisMaxRange; thisMaxRate = thisRateMultiplier .add(thisBaseRate) .mul(thisKinkLevel) .div(WEI_PERCENT_PRECISION); nextRate = utilRate .mul(SafeMath.sub(thisMaxScaleRate, thisMaxRate)) .div(thisMaxRange) .add(thisMaxRate); } else { nextRate = utilRate .mul(thisRateMultiplier) .div(WEI_PERCENT_PRECISION) .add(thisBaseRate); thisMinRate = thisBaseRate; thisMaxRate = thisRateMultiplier .add(thisBaseRate); if (nextRate < thisMinRate) nextRate = thisMinRate; else if (nextRate > thisMaxRate) nextRate = thisMaxRate; } } function _getAllInterest() internal view returns ( uint256 interestOwedPerDay, uint256 interestUnPaid) { // interestPaid, interestPaidDate, interestOwedPerDay, interestUnPaid, interestFeePercent, principalTotal uint256 interestFeePercent; (,,interestOwedPerDay,interestUnPaid,interestFeePercent,) = ProtocolLike(sovrynContractAddress).getLenderInterestData( address(this), loanTokenAddress ); interestUnPaid = interestUnPaid .mul(SafeMath.sub(10**20, interestFeePercent)) .div(10**20); } function _getMarginBorrowAmountAndRate( uint256 leverageAmount, uint256 depositAmount) internal view returns (uint256 borrowAmount, uint256 interestRate) { uint256 initialMargin = SafeMath.div(10**38, leverageAmount); interestRate = _nextBorrowInterestRate2( depositAmount .mul(10**20) .div(initialMargin), _totalAssetSupply(0) ); // assumes that loan, collateral, and interest token are the same borrowAmount = depositAmount .mul(10**40) .div(_adjustValue( interestRate, 2419200, // 28 day duration for margin trades initialMargin)) .div(initialMargin); } function _totalAssetSupply( uint256 interestUnPaid) internal view returns (uint256 assetSupply) { if (totalSupply_ != 0) { uint256 assetsBalance = _flTotalAssetSupply; // temporary locked totalAssetSupply during a flash loan transaction if (assetsBalance == 0) { assetsBalance = _underlyingBalance() .add(totalAssetBorrow()); } return assetsBalance .add(interestUnPaid); } } /** * used to read externally from the smart contract to see if a function is paused * returns a bool * */ function checkPause(string memory funcId) public view returns (bool isPaused){ bytes4 sig = bytes4(keccak256(abi.encodePacked(funcId))); bytes32 slot = keccak256(abi.encodePacked(sig, uint256(0xd46a704bc285dbd6ff5ad3863506260b1df02812f4f857c8cc852317a6ac64f2))); assembly { isPaused := sload(slot) } return isPaused; } /** * used for internal verification if the called function is paused. * throws an exception in case it's not * */ function _checkPause() internal view { //keccak256("iToken_FunctionPause") bytes32 slot = keccak256(abi.encodePacked(msg.sig, uint256(0xd46a704bc285dbd6ff5ad3863506260b1df02812f4f857c8cc852317a6ac64f2))); bool isPaused; assembly { isPaused := sload(slot) } require(!isPaused, "unauthorized"); } function _adjustValue( uint256 interestRate, uint256 maxDuration, uint256 marginAmount) internal pure returns (uint256) { return maxDuration != 0 ? interestRate .mul(10**20) .div(31536000) // 86400 * 365 .mul(maxDuration) .div(marginAmount) .add(10**20) : 10**20; } function _utilizationRate( uint256 assetBorrow, uint256 assetSupply) internal pure returns (uint256) { if (assetBorrow != 0 && assetSupply != 0) { // U = total_borrow / total_supply return assetBorrow .mul(10**20) .div(assetSupply); } } /* Owner-Only functions */ function updateSettings( address settingsTarget, bytes memory callData) public onlyOwner { address currentTarget = target_; target_ = settingsTarget; (bool result,) = address(this).call(callData); uint256 size; uint256 ptr; assembly { size := returndatasize ptr := mload(0x40) returndatacopy(ptr, 0, size) if eq(result, 0) { revert(ptr, size) } } target_ = currentTarget; assembly { return(ptr, size) } } }
borrows funds from the pool. The underlying loan token may not be used as collateral. loanId the ID of the loan, 0 for a new loan withdrawAmount the amount to be withdrawn (actually borrowed) initialLoanDuration the duration of the loan in seconds. if the loan is not paid back until then, it'll need to be rolled over collateralTokenSent the amount of collateral token sent (150% of the withdrawn amount worth in collateral tokenns) collateralTokenAddress the address of the tokenn to be used as collateral. cannot be the loan token address borrower the one paying for the collateral receiver the one receiving the withdrawn amount /temporary: limit transaction size
function borrow( uint256 withdrawAmount, address borrower, address receiver, public payable { require(withdrawAmount != 0, "6"); _checkPause(); if(transactionLimit[collateralTokenAddress] > 0) require(collateralTokenSent <= transactionLimit[collateralTokenAddress]); require(msg.value == 0 || msg.value == collateralTokenSent, "7"); require(collateralTokenSent != 0 || loanId != 0, "8"); require(collateralTokenAddress != address(0) || msg.value != 0 || loanId != 0, "9"); if (collateralTokenAddress == address(0)) { collateralTokenAddress = wrbtcTokenAddress; } require(collateralTokenAddress != loanTokenAddress, "10"); _settleInterest(); address[4] memory sentAddresses; uint256[5] memory sentAmounts; sentAddresses[1] = borrower; sentAddresses[2] = receiver; sentAmounts[1] = withdrawAmount; sentAmounts[1], initialLoanDuration ); return _borrowOrTrade( loanId, withdrawAmount, collateralTokenAddress, sentAddresses, sentAmounts, ); }
1,834,994
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.7.0; pragma abicoder v2; contract DeadPool { /* Types */ enum eventStatus{open, finished, closed} enum bidStatus{open, closed} struct bid { uint id; uint256 name; address[] whoBet; uint amountReceived; bidStatus status; } struct betEvent { uint id; bytes32 name; address creator; address arbitrator; uint256 winner; uint arbitratorFee; uint minBid; // value in wei uint maxBid; // value in wei bid[] bids; bet[] bets; eventStatus status; } struct bet { address person; uint256 bidName; uint amount; uint256 timestamp; } /* Storage */ address public owner; mapping(address => betEvent[]) public betEvents; mapping(address => uint) public pendingWithdrawals; /* Events */ // event eventCreated(uint id, address creator); // event betMade(uint value, uint id); // event eventStatusChanged(uint status); // event withdrawalDone(uint amount); /* Modifiers */ modifier onlyOwner(){ if (msg.sender == owner) { _; } } modifier onlyOpen(address creator, uint eventId){ if (betEvents[creator][eventId].status == eventStatus.open) { _; } } modifier onlyFinished(address creator, uint eventId){ if (betEvents[creator][eventId].status == eventStatus.finished) { _; } } modifier onlyArbitrator(address creator, uint eventId){ if (msg.sender == betEvents[creator][eventId].arbitrator) { _; } } modifier onlyOpenAndArbitrator(address creator, uint eventId){ if (betEvents[creator][eventId].status == eventStatus.open && msg.sender == betEvents[creator][eventId].arbitrator) { _; } } modifier onlyFinishedAndArbitrator(address creator, uint eventId){ if (betEvents[creator][eventId].status == eventStatus.finished && msg.sender == betEvents[creator][eventId].arbitrator) { _; } } /* Methods */ constructor() { owner = msg.sender; } fallback() external payable { // custom function code } receive() external payable { // custom function code } bid public newBid; betEvent public newEvent; bet public newBet; function createEvent(address arbitrator, bytes32 name, uint fee, uint minBid, uint maxBid) external onlyOwner { require(fee < 100, "Fee must be lower than 100."); /* check whether event with such name already exist */ bool found = false; for (uint x = 0; x < betEvents[msg.sender].length; x++) { if (betEvents[msg.sender][x].name == name) { found = true; } } require(!found, "Event with same name already exists."); uint newId = betEvents[msg.sender].length; newEvent.id = newId; newEvent.name = name; newEvent.arbitrator = arbitrator; newEvent.status = eventStatus.open; newEvent.creator = msg.sender; newEvent.minBid = minBid; newEvent.maxBid = maxBid; newEvent.arbitratorFee = fee; betEvents[msg.sender].push(newEvent); // emit eventCreated(newId, msg.sender); } function finishEvent(address creator, uint eventId) external onlyOpenAndArbitrator(creator, eventId) { betEvents[creator][eventId].status = eventStatus.finished; // emit eventStatusChanged(1); } function _addBid(address creator, uint eventId, uint256 bidName) private onlyOpen(creator, eventId) { uint newBidId = 0; bool found = findBid(creator, eventId, bidName); if (!found) { newBidId = betEvents[creator][eventId].bids.length; newBid.id = newBidId; newBid.name = bidName; newBid.status = bidStatus.open; betEvents[creator][eventId].bids.push(newBid); } } function addBid(address creator, uint eventId, uint256 bidName) external onlyOpen(creator, eventId) { _addBid(creator, eventId, bidName); } function addBids(address creator, uint eventId, uint256[] calldata bidNames) external onlyOpen(creator, eventId) { for (uint i = 0; i < bidNames.length; i++) { _addBid(creator, eventId, bidNames[i]); } } function _closeBid(address creator, uint eventId, uint256 bidName) private onlyOpenAndArbitrator(creator, eventId) { for (uint i = 0; i < betEvents[creator][eventId].bids.length; i++) { if (betEvents[creator][eventId].bids[i].name == bidName) { betEvents[creator][eventId].bids[i].status = bidStatus.closed; } } } function closeBid(address creator, uint eventId, uint256 bidName) external onlyOpenAndArbitrator(creator, eventId) { _closeBid(creator, eventId, bidName); } function closeBids(address creator, uint eventId, uint256[] calldata bidNames) external onlyOpenAndArbitrator(creator, eventId) { for (uint i = 0; i < bidNames.length; i++) { _closeBid(creator, eventId, bidNames[i]); } } // function openBid(address creator, uint eventId, bytes32 bidName) external // onlyOpen(creator, eventId) onlyArbitrator(creator, eventId) { // for (uint i = 0; i < betEvents[creator][eventId].bids.length; i++) { // if (betEvents[creator][eventId].bids[i].name == bidName) { // betEvents[creator][eventId].bids[i].status = bidStatus.open; // } // } // } function makeBet(address creator, uint eventId, uint256 bidName) public payable onlyOpen(creator, eventId) { uint256 minDate = (block.timestamp / (60 * 60 * 24) + 1) * (60 * 60 * 24); require(bidName >= minDate, "Bid must be more than today."); /* check whether bid with given name actually exists */ bool found = findBid(creator, eventId, bidName); if (!found) { this.addBid(creator, eventId, bidName); } for (uint i = 0; i < betEvents[creator][eventId].bids.length; i++) { if (betEvents[creator][eventId].bids[i].name == bidName) { bid storage foundBid = betEvents[creator][eventId].bids[i]; found = true; require(foundBid.status == bidStatus.open, "Bid is closed."); //check for minimal amount if (betEvents[creator][eventId].minBid > 0) { require(msg.value >= betEvents[creator][eventId].minBid, "Min amount error."); } //check for maximal amount if (betEvents[creator][eventId].maxBid > 0) { require(msg.value <= betEvents[creator][eventId].maxBid, "Max amount error."); } foundBid.whoBet.push(msg.sender); foundBid.amountReceived += msg.value; newBet.person = msg.sender; newBet.amount = msg.value; newBet.bidName = bidName; newBet.timestamp = block.timestamp; betEvents[creator][eventId].bets.push(newBet); // emit betMade(msg.value, newBetId); } } require(found, "Bid not found."); } function determineWinner(address creator, uint eventId, uint256 bidName) external onlyFinishedAndArbitrator(creator, eventId) { require(findBid(creator, eventId, bidName)); betEvent storage cEvent = betEvents[creator][eventId]; cEvent.winner = bidName; uint amountLost; uint amountWon; uint lostBetsLen; /* Calculating amount of all won and lost bets */ for (uint x = 0; x < cEvent.bets.length; x++) { uint betAmount = cEvent.bets[x].amount; if (cEvent.bets[x].bidName == cEvent.winner) { amountWon += betAmount; pendingWithdrawals[cEvent.bets[x].person] += betAmount; } else { lostBetsLen++; amountLost += betAmount; } } uint arbitratorAmount = amountLost / 100 * cEvent.arbitratorFee; pendingWithdrawals[cEvent.arbitrator] += arbitratorAmount; amountLost -= arbitratorAmount; /* If we do have win bets */ if (amountWon > 0) { for (uint x = 0; x < cEvent.bets.length; x++) { if (cEvent.bets[x].bidName == cEvent.winner) { uint wonBetPercentage = percent(cEvent.bets[x].amount, amountWon, 2); pendingWithdrawals[cEvent.bets[x].person] += (amountLost / 100) * wonBetPercentage; } } } else { /* If we don't have any bets won, we pay all the funds back except arbitrator fee */ for (uint x = 0; x < cEvent.bets.length; x++) { pendingWithdrawals[cEvent.bets[x].person] += cEvent.bets[x].amount - ((cEvent.bets[x].amount / 100) * cEvent.arbitratorFee); } } cEvent.status = eventStatus.closed; // emit eventStatusChanged(2); } function withdraw(address payable person) private { uint amount = pendingWithdrawals[person]; pendingWithdrawals[person] = 0; person.transfer(amount); // emit withdrawalDone(amount); } function requestWithdraw() external { require(pendingWithdrawals[msg.sender] != 0, "No withdrawal available."); withdraw(payable(msg.sender)); } function findBid(address creator, uint eventId, uint256 bidName) private view returns (bool){ for (uint i = 0; i < betEvents[creator][eventId].bids.length; i++) { if (betEvents[creator][eventId].bids[i].name == bidName) { return true; } } return false; } function percent(uint numerator, uint denominator, uint precision) public pure returns (uint quotient) { // caution, check safe-to-multiply here uint _numerator = numerator * 10 ** (precision + 1); // with rounding of last digit uint _quotient = ((_numerator / denominator) + 5) / 10; return (_quotient); } function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { uint8 i = 0; while (i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } /* Getters */ function getBetEvents(address creator) external view returns (betEvent[] memory){ return betEvents[creator]; } // // function getBetEvent(address creator, uint eventId) external view returns (betEvent memory){ // return betEvents[creator][eventId]; // } // // function getBidsNum(address creator, uint eventId) external view returns (uint){ // return betEvents[creator][eventId].bids.length; // } // function getBids(address creator, uint eventId) external view returns (bid[] memory){ return betEvents[creator][eventId].bids; } // // function getBid(address creator, uint eventId, uint bidId) external view returns (uint, bytes32, uint){ // bid storage foundBid = betEvents[creator][eventId].bids[bidId]; // return (foundBid.id, foundBid.name, foundBid.amountReceived); // } // // function getBetsNums(address creator, uint eventId) external view returns (uint){ // return betEvents[creator][eventId].bets.length; // } // // function getWhoBet(address creator, uint eventId, uint bidId) external view returns (address[] memory){ // return betEvents[creator][eventId].bids[bidId].whoBet; // } // function getBets(address creator, uint eventId) external view returns (bet[] memory){ return betEvents[creator][eventId].bets; } // // function getBet(address creator, uint eventId, uint betId) external view returns (address, bytes32, uint){ // bet storage foundBet = betEvents[creator][eventId].bets[betId]; // return (foundBet.person, foundBet.bidName, foundBet.amount); // } // // function getEventId(address creator, bytes32 eventName) external view returns (uint, bool){ // for (uint i = 0; i < betEvents[creator].length; i++) { // if (betEvents[creator][i].name == eventName) { // return (betEvents[creator][i].id, true); // } // } // return (0, false); // } }
caution, check safe-to-multiply here with rounding of last digit
function percent(uint numerator, uint denominator, uint precision) public pure returns (uint quotient) { uint _numerator = numerator * 10 ** (precision + 1); uint _quotient = ((_numerator / denominator) + 5) / 10; return (_quotient); }
13,879,330
pragma solidity ^0.4.24; import "./strings.sol"; import "./Owned.sol"; import "./ERC20Token.sol"; import "./PortalNetworkTokenConfig.sol"; contract PortalNetworkToken is Owned, ERC20Token, PortalNetworkTokenConfig { using strings for *; address public prtAccrueAddr; address public auctionPoolAddr; mapping (string => address) protocolRegistrarAddr; event PRTAccrue( address indexed _owner, string indexed _name, string indexed _protocol, uint _registrationDate, uint _expiredate, uint256 _value ); event UpgradeProtocolRegistrar(string _protocol, address _protocolRegistrarAddr); event UpgradePRTAccrue(address _prtAccrueAddr); event UpgradeAuctionPool(address _auctionPoolAddr); constructor(address _prtAccrueAddr, address _auctionPoolAddr) public ERC20Token(TOKEN_NAME, TOKEN_SYMBOL, TOKEN_DECIMALS, TOKEN_TOTALSUPPLY, msg.sender) { prtAccrueAddr = _prtAccrueAddr; auctionPoolAddr = _auctionPoolAddr; } struct Metadata { string name; string protocol; address owner; uint registrationDate; uint expireDate; uint value; } mapping (string => Metadata) _metadata; /** * @dev Only available for the ProtocolRegistrar contract * * @param _protocol The protocol of the BNS */ modifier onlyProtocolRegistrar(string _protocol) { require(msg.sender == address(protocolRegistrarAddr[_protocol]), "sender is not ProtocolRegistrar"); _; } /** * @dev Transfer PRT to auction pool at the auction process * * @param _from The from address who need to lock the RPT * @param _value The tokne of the bidding price * @param _protocol The protocol of the BNS */ function transferToAuctionPool(address _from, uint256 _value, string _protocol) external onlyProtocolRegistrar(_protocol) returns (bool) { return _transferToAuctionPool(_from, _value); } /** * @dev The internal function of transferToAuctionPool * * @param _from The from address who need to lock the RPT * @param _value The token of the bidding price */ function _transferToAuctionPool(address _from, uint256 _value) internal returns (bool) { if (_value < 0 || balances[_from] < _value) { return false; } balances[_from] = balances[_from].sub(_value); balances[auctionPoolAddr] = balances[auctionPoolAddr].add(_value); return true; } /** * @dev Transfer PRT to the origin owner * * @param _to The address of the origin sender * @param _value The token of the origin amount * @param _protocol The protocol of the BNS */ function transferBackToOwner(address _to, uint256 _value, string _protocol) external onlyProtocolRegistrar(_protocol) returns (bool) { return _transferBackToOwner(_to, _value); } /** * @dev The internal function of transferBackToOwner * * @param _to The address of the origin sender * @param _value The token of the origin amount */ function _transferBackToOwner(address _to, uint256 _value) internal returns (bool) { if (_value < 0 || balances[auctionPoolAddr] < _value) { return false; } balances[auctionPoolAddr] = balances[auctionPoolAddr].sub(_value); balances[_to] = balances[_to].add(_value); return true; } /** * @dev The function to store the metadata of BNS * * @param _from The owner of the BNS * @param _value The final amount of the BNS * @param _name The name of the BNS * @param _protocol The protocol of the BNS * @param _expireDate The expire date of the BNS * @param _registrationDate The registration date of the BNS */ function transferWithMetadata( address _from, uint256 _value, string _name, string _protocol, uint _expireDate, uint _registrationDate ) external onlyProtocolRegistrar(_protocol) returns (bool) { return _transferWithMetadata(_from, _value, _name, _protocol, _expireDate, _registrationDate); } /** * @dev The internal function of transferWithMetadata * * @param _from The owner of the BNS * @param _value The final amount of the BNS * @param _name The name of the BNS * @param _protocol The protocol of the BNS * @param _expireDate The expire date of the BNS * @param _registrationDate The registration date of the BNS */ function _transferWithMetadata( address _from, uint256 _value, string _name, string _protocol, uint _expireDate, uint _registrationDate ) internal returns (bool) { // TODO finalize and move the Token from AuctionPool address to PRTAccrue address balances[auctionPoolAddr] = balances[auctionPoolAddr].sub(_value); balances[prtAccrueAddr] = balances[prtAccrueAddr].add(_value); string memory protocol = ".".toSlice().concat(_protocol.toSlice()); string memory bns = _name.toSlice().concat(protocol.toSlice()); Metadata storage newMetadata = _metadata[bns]; newMetadata.name = _name; newMetadata.protocol = _protocol; newMetadata.owner = _from; newMetadata.registrationDate = _registrationDate; newMetadata.expireDate = _expireDate; newMetadata.value = _value; emit Transfer(_from, prtAccrueAddr, _value); emit PRTAccrue(_from, _name, _protocol, _registrationDate, _expireDate, _value); return true; } /** * @dev Get the metadata of the BNS * * @param _name The name of the BNS * @param _protocol The protocol of the BNS */ function metadata(string _name, string _protocol) public view returns (address, uint, uint, uint256) { string memory protocol = ".".toSlice().concat(_protocol.toSlice()); string memory bns = _name.toSlice().concat(protocol.toSlice()); Metadata storage m = _metadata[bns]; return (m.owner, m.registrationDate, m.expireDate, m.value); } /** * @dev set metadata of BNS * * @param _name The name of the BNS * @param _protocol The protocol of the BNS * @param _owner The owner of the BNS * @param _registrationDate The registration date of the BNS * @param _expireDate The expire date of the BNS * @param _value The final amount of the BNS */ function setMetadata( string _name, string _protocol, address _owner, uint _registrationDate, uint _expireDate, uint _value) external onlyProtocolRegistrar(_protocol) returns (bool) { return _setMetadata(_name, _protocol, _owner, _registrationDate, _expireDate, _value); } /** * @dev The internal function of setMetadata * * @param _name The name of the BNS * @param _protocol The protocol of the BNS * @param _owner The owner of the BNS * @param _registrationDate The registration date of the BNS * @param _expireDate The expire date of the BNS * @param _value The final amount of the BNS */ function _setMetadata( string _name, string _protocol, address _owner, uint _registrationDate, uint _expireDate, uint _value) internal returns (bool) { string memory protocol = ".".toSlice().concat(_protocol.toSlice()); string memory bns = _name.toSlice().concat(protocol.toSlice()); Metadata storage newMetadata = _metadata[bns]; newMetadata.name = _name; newMetadata.protocol = _protocol; newMetadata.owner = _owner; newMetadata.registrationDate = _registrationDate; newMetadata.expireDate = _expireDate; newMetadata.value = _value; // TODO store data return true; } /** * @dev Update the address of the PRT accrue pool * * @param _newPRTAccrue new PRT accrue address */ function upgradePRTAccrue(address _newPRTAccrue) external onlyOwner { require(_newPRTAccrue != address(0), "PRTAccrue address can not be 0"); require(_newPRTAccrue != address(this), "PRTAccrue address can not as same as PortalNetworkToken address"); require(_newPRTAccrue != prtAccrueAddr, "PRTAccrue address is as same as current address"); prtAccrueAddr = _newPRTAccrue; emit UpgradePRTAccrue(_newPRTAccrue); } /** * @dev Update the Universal Registrar contract * * @param _protocol The protocol of the BNS * @param _newProtocolRegistrar New ProtocolRegistrar address */ function upgradeProtocolRegistrar(string _protocol, address _newProtocolRegistrar) external onlyOwner { require(_newProtocolRegistrar != address(0), "ProtocolRegistrar address can not be 0"); require(_newProtocolRegistrar != address(this), "ProtocolRegistrar address can not as same as PortalNetworkToken address"); require(_newProtocolRegistrar != protocolRegistrarAddr[_protocol], "ProtocolRegistrar address is as same as current address"); protocolRegistrarAddr[_protocol] = _newProtocolRegistrar; emit UpgradeProtocolRegistrar(_protocol, _newProtocolRegistrar); } /** * @dev Update the auction pool address * * @param _newAuctionPool New auction pool address */ function upgradeAuctionPool(address _newAuctionPool) external onlyOwner { require(_newAuctionPool != address(0), "AuctionPool address can not be 0"); require(_newAuctionPool != address(this), "AuctionPool address can not as same as PortalNetworkToken address"); require(_newAuctionPool != auctionPoolAddr, "AuctionPool address is as same as current address"); auctionPoolAddr = _newAuctionPool; emit UpgradeAuctionPool(_newAuctionPool); } /** * @dev Return protocol registrar address * * @param _protocol The protocol of the BNS */ function protocolRegistrar(string _protocol) public view returns (address) { return protocolRegistrarAddr[_protocol]; } }
The internal function of setMetadata _name The name of the BNS _protocol The protocol of the BNS _owner The owner of the BNS _registrationDate The registration date of the BNS _expireDate The expire date of the BNS _value The final amount of the BNS/ TODO store data
function _setMetadata( string _name, string _protocol, address _owner, uint _registrationDate, uint _expireDate, uint _value) internal returns (bool) { string memory protocol = ".".toSlice().concat(_protocol.toSlice()); string memory bns = _name.toSlice().concat(protocol.toSlice()); Metadata storage newMetadata = _metadata[bns]; newMetadata.name = _name; newMetadata.protocol = _protocol; newMetadata.owner = _owner; newMetadata.registrationDate = _registrationDate; newMetadata.expireDate = _expireDate; newMetadata.value = _value; return true; }
14,027,641
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import "./abstracts/fujiERC1155/FujiBaseERC1155.sol"; import "./abstracts/fujiERC1155/F1155Manager.sol"; import "./abstracts/claimable/ClaimableUpgradeable.sol"; import "./interfaces/IFujiERC1155.sol"; import "./libraries/WadRayMath.sol"; import "./libraries/Errors.sol"; contract FujiERC1155 is IFujiERC1155, FujiBaseERC1155, F1155Manager { using WadRayMath for uint256; // FujiERC1155 Asset ID Mapping // AssetType => asset reference address => ERC1155 Asset ID mapping(AssetType => mapping(address => uint256)) public assetIDs; // Control mapping that returns the AssetType of an AssetID mapping(uint256 => AssetType) public assetIDtype; uint64 public override qtyOfManagedAssets; // Asset ID Liquidity Index mapping // AssetId => Liquidity index for asset ID mapping(uint256 => uint256) public indexes; function initialize() external initializer { __ERC165_init(); __Context_init(); __Climable_init(); } /** * @dev Updates Index of AssetID * @param _assetID: ERC1155 ID of the asset which state will be updated. * @param newBalance: Amount **/ function updateState(uint256 _assetID, uint256 newBalance) external override onlyPermit { uint256 total = totalSupply(_assetID); if (newBalance > 0 && total > 0 && newBalance > total) { uint256 diff = newBalance - total; uint256 amountToIndexRatio = (diff.wadToRay()).rayDiv(total.wadToRay()); uint256 result = amountToIndexRatio + WadRayMath.ray(); result = result.rayMul(indexes[_assetID]); require(result <= type(uint128).max, Errors.VL_INDEX_OVERFLOW); indexes[_assetID] = uint128(result); // TODO: calculate interest rate for a fujiOptimizer Fee. } } /** * @dev Returns the total supply of Asset_ID with accrued interest. * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function totalSupply(uint256 _assetID) public view virtual override returns (uint256) { // TODO: include interest accrued by Fuji OptimizerFee return super.totalSupply(_assetID).rayMul(indexes[_assetID]); } /** * @dev Returns the scaled total supply of the token ID. Represents sum(token ID Principal /index) * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function scaledTotalSupply(uint256 _assetID) public view virtual returns (uint256) { return super.totalSupply(_assetID); } /** * @dev Returns the principal + accrued interest balance of the user * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function balanceOf(address _account, uint256 _assetID) public view override(FujiBaseERC1155, IFujiERC1155) returns (uint256) { uint256 scaledBalance = super.balanceOf(_account, _assetID); if (scaledBalance == 0) { return 0; } // TODO: include interest accrued by Fuji OptimizerFee return scaledBalance.rayMul(indexes[_assetID]); } /** * @dev Returns Scaled Balance of the user (e.g. balance/index) * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function scaledBalanceOf(address _account, uint256 _assetID) public view virtual returns (uint256) { return super.balanceOf(_account, _assetID); } /** * @dev Mints tokens for Collateral and Debt receipts for the Fuji Protocol * Emits a {TransferSingle} event. * Requirements: * - `_account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. * - `_amount` should be in WAD */ function mint( address _account, uint256 _id, uint256 _amount, bytes memory _data ) external override onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); address operator = _msgSender(); uint256 accountBalance = _balances[_id][_account]; uint256 assetTotalBalance = _totalSupply[_id]; uint256 amountScaled = _amount.rayDiv(indexes[_id]); require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT); _balances[_id][_account] = accountBalance + amountScaled; _totalSupply[_id] = assetTotalBalance + amountScaled; emit TransferSingle(operator, address(0), _account, _id, _amount); _doSafeTransferAcceptanceCheck(operator, address(0), _account, _id, _amount, _data); } /** * @dev [Batched] version of {mint}. * Requirements: * - `_ids` and `_amounts` must have the same length. * - If `_to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function mintBatch( address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) external onlyPermit { require(_to != address(0), Errors.VL_ZERO_ADDR_1155); require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR); address operator = _msgSender(); uint256 accountBalance; uint256 assetTotalBalance; uint256 amountScaled; for (uint256 i = 0; i < _ids.length; i++) { accountBalance = _balances[_ids[i]][_to]; assetTotalBalance = _totalSupply[_ids[i]]; amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]); require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT); _balances[_ids[i]][_to] = accountBalance + amountScaled; _totalSupply[_ids[i]] = assetTotalBalance + amountScaled; } emit TransferBatch(operator, address(0), _to, _ids, _amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), _to, _ids, _amounts, _data); } /** * @dev Destroys `_amount` receipt tokens of token type `_id` from `account` for the Fuji Protocol * Requirements: * - `account` cannot be the zero address. * - `account` must have at least `_amount` tokens of token type `_id`. * - `_amount` should be in WAD */ function burn( address _account, uint256 _id, uint256 _amount ) external override onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); address operator = _msgSender(); uint256 accountBalance = _balances[_id][_account]; uint256 assetTotalBalance = _totalSupply[_id]; uint256 amountScaled = _amount.rayDiv(indexes[_id]); require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT); _balances[_id][_account] = accountBalance - amountScaled; _totalSupply[_id] = assetTotalBalance - amountScaled; emit TransferSingle(operator, _account, address(0), _id, _amount); } /** * @dev [Batched] version of {burn}. * Requirements: * - `_ids` and `_amounts` must have the same length. */ function burnBatch( address _account, uint256[] memory _ids, uint256[] memory _amounts ) external onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR); address operator = _msgSender(); uint256 accountBalance; uint256 assetTotalBalance; uint256 amountScaled; for (uint256 i = 0; i < _ids.length; i++) { uint256 amount = _amounts[i]; accountBalance = _balances[_ids[i]][_account]; assetTotalBalance = _totalSupply[_ids[i]]; amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]); require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT); _balances[_ids[i]][_account] = accountBalance - amount; _totalSupply[_ids[i]] = assetTotalBalance - amount; } emit TransferBatch(operator, _account, address(0), _ids, _amounts); } //Getter Functions /** * @dev Getter Function for the Asset ID locally managed * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset * @param _addr: Reference Address of the Asset */ function getAssetID(AssetType _type, address _addr) external view override returns (uint256 id) { id = assetIDs[_type][_addr]; require(id <= qtyOfManagedAssets, Errors.VL_INVALID_ASSETID_1155); } //Setter Functions /** * @dev Sets a new URI for all token types, by relying on the token type ID */ function setURI(string memory _newUri) public onlyOwner { _uri = _newUri; } /** * @dev Adds and initializes liquidity index of a new asset in FujiERC1155 * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset * @param _addr: Reference Address of the Asset */ function addInitializeAsset(AssetType _type, address _addr) external override onlyPermit returns (uint64) { require(assetIDs[_type][_addr] == 0, Errors.VL_ASSET_EXISTS); assetIDs[_type][_addr] = qtyOfManagedAssets; assetIDtype[qtyOfManagedAssets] = _type; //Initialize the liquidity Index indexes[qtyOfManagedAssets] = WadRayMath.ray(); qtyOfManagedAssets++; return qtyOfManagedAssets - 1; } } // 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 "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/extensions/IERC1155MetadataURIUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../libraries/Errors.sol"; /** * * @dev Implementation of the Base ERC1155 multi-token standard functions * for Fuji Protocol control of User collaterals and borrow debt positions. * Originally based on Openzeppelin * */ abstract contract FujiBaseERC1155 is IERC1155Upgradeable, ERC165Upgradeable, ContextUpgradeable { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) internal _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) internal _operatorApprovals; // Mapping from token ID to totalSupply mapping(uint256 => uint256) internal _totalSupply; //URI for all token types by relying on ID substitution //https://token.fujiDao.org/{id}.json string internal _uri; /** * @return The total supply of a token id **/ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155Upgradeable).interfaceId || interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * Requirements: * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), Errors.VL_ZERO_ADDR_1155); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * Requirements: * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view override returns (uint256[] memory) { require(accounts.length == ids.length, Errors.VL_INPUT_ERROR); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, Errors.VL_INPUT_ERROR); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address, // from address, // to uint256, // id uint256, // amount bytes memory // data ) public virtual override { revert(Errors.VL_ERC1155_NOT_TRANSFERABLE); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address, // from address, // to uint256[] memory, // ids uint256[] memory, // amounts bytes memory // data ) public virtual override { revert(Errors.VL_ERC1155_NOT_TRANSFERABLE); } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) internal { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) { revert(Errors.VL_RECEIVER_REJECT_1155); } } catch Error(string memory reason) { revert(reason); } catch { revert(Errors.VL_RECEIVER_CONTRACT_NON_1155); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) { revert(Errors.VL_RECEIVER_REJECT_1155); } } catch Error(string memory reason) { revert(reason); } catch { revert(Errors.VL_RECEIVER_CONTRACT_NON_1155); } } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "./FujiBaseERC1155.sol"; import "../claimable/ClaimableUpgradeable.sol"; import "../../interfaces/IFujiERC1155.sol"; import "../../libraries/WadRayMath.sol"; import "../../libraries/Errors.sol"; abstract contract F1155Manager is ClaimableUpgradeable { using Address for address; // Controls for Mint-Burn Operations mapping(address => bool) public addrPermit; modifier onlyPermit() { require(addrPermit[_msgSender()] || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED); _; } function setPermit(address _address, bool _permit) public onlyOwner { require((_address).isContract(), Errors.VL_NOT_A_CONTRACT); addrPermit[_address] = _permit; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; abstract contract ClaimableUpgradeable is Initializable, ContextUpgradeable { address private _owner; address public pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event NewPendingOwner(address indexed owner); function __Climable_init() internal initializer { __Context_init_unchained(); __Climable_init_unchained(); } function __Climable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(_msgSender() == owner(), "Ownable: caller is not the owner"); _; } modifier onlyPendingOwner() { require(_msgSender() == pendingOwner); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(owner(), address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(pendingOwner == address(0)); pendingOwner = newOwner; emit NewPendingOwner(newOwner); } function cancelTransferOwnership() public onlyOwner { require(pendingOwner != address(0)); delete pendingOwner; emit NewPendingOwner(address(0)); } function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner(), pendingOwner); _owner = pendingOwner; delete pendingOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IFujiERC1155 { //Asset Types enum AssetType { //uint8 = 0 collateralToken, //uint8 = 1 debtToken } //General Getter Functions function getAssetID(AssetType _type, address _assetAddr) external view returns (uint256); function qtyOfManagedAssets() external view returns (uint64); function balanceOf(address _account, uint256 _id) external view returns (uint256); // function splitBalanceOf(address account,uint256 _AssetID) external view returns (uint256,uint256); // function balanceOfBatchType(address account, AssetType _Type) external view returns (uint256); //Permit Controlled Functions function mint( address _account, uint256 _id, uint256 _amount, bytes memory _data ) external; function burn( address _account, uint256 _id, uint256 _amount ) external; function updateState(uint256 _assetID, uint256 _newBalance) external; function addInitializeAsset(AssetType _type, address _addr) external returns (uint64); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.0; import { Errors } from "./Errors.sol"; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant _WAD = 1e18; uint256 internal constant _HALF_WAD = _WAD / 2; uint256 internal constant _RAY = 1e27; uint256 internal constant _HALF_RAY = _RAY / 2; uint256 internal constant _WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return _RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return _WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return _HALF_RAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return _HALF_WAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - _HALF_WAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + _HALF_WAD) / _WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / _WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * _WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - _HALF_RAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + _HALF_RAY) / _RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / _RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * _RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = _WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / _WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * _WAD_RAY_RATIO; require(result / _WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.0; /** * @title Errors library * @author Fuji * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = Validation Logic 100 series * - MATH = Math libraries 200 series * - RF = Refinancing 300 series * - VLT = vault 400 series * - SP = Special 900 series */ library Errors { //Errors string public constant VL_INDEX_OVERFLOW = "100"; // index overflows uint128 string public constant VL_INVALID_MINT_AMOUNT = "101"; //invalid amount to mint string public constant VL_INVALID_BURN_AMOUNT = "102"; //invalid amount to burn string public constant VL_AMOUNT_ERROR = "103"; //Input value >0, and for ETH msg.value and amount shall match string public constant VL_INVALID_WITHDRAW_AMOUNT = "104"; //Withdraw amount exceeds provided collateral, or falls undercollaterized string public constant VL_INVALID_BORROW_AMOUNT = "105"; //Borrow amount does not meet collaterization string public constant VL_NO_DEBT_TO_PAYBACK = "106"; //Msg sender has no debt amount to be payback string public constant VL_MISSING_ERC20_ALLOWANCE = "107"; //Msg sender has not approved ERC20 full amount to transfer string public constant VL_USER_NOT_LIQUIDATABLE = "108"; //User debt position is not liquidatable string public constant VL_DEBT_LESS_THAN_AMOUNT = "109"; //User debt is less than amount to partial close string public constant VL_PROVIDER_ALREADY_ADDED = "110"; // Provider is already added in Provider Array string public constant VL_NOT_AUTHORIZED = "111"; //Not authorized string public constant VL_INVALID_COLLATERAL = "112"; //There is no Collateral, or Collateral is not in active in vault string public constant VL_NO_ERC20_BALANCE = "113"; //User does not have ERC20 balance string public constant VL_INPUT_ERROR = "114"; //Check inputs. For ERC1155 batch functions, array sizes should match. string public constant VL_ASSET_EXISTS = "115"; //Asset intended to be added already exists in FujiERC1155 string public constant VL_ZERO_ADDR_1155 = "116"; //ERC1155: balance/transfer for zero address string public constant VL_NOT_A_CONTRACT = "117"; //Address is not a contract. string public constant VL_INVALID_ASSETID_1155 = "118"; //ERC1155 Asset ID is invalid. string public constant VL_NO_ERC1155_BALANCE = "119"; //ERC1155: insufficient balance for transfer. string public constant VL_MISSING_ERC1155_APPROVAL = "120"; //ERC1155: transfer caller is not owner nor approved. string public constant VL_RECEIVER_REJECT_1155 = "121"; //ERC1155Receiver rejected tokens string public constant VL_RECEIVER_CONTRACT_NON_1155 = "122"; //ERC1155: transfer to non ERC1155Receiver implementer string public constant VL_OPTIMIZER_FEE_SMALL = "123"; //Fuji OptimizerFee has to be > 1 RAY (1e27) string public constant VL_UNDERCOLLATERIZED_ERROR = "124"; // Flashloan-Flashclose cannot be used when User's collateral is worth less than intended debt position to close. string public constant VL_MINIMUM_PAYBACK_ERROR = "125"; // Minimum Amount payback should be at least Fuji Optimizerfee accrued interest. string public constant VL_HARVESTING_FAILED = "126"; // Harvesting Function failed, check provided _farmProtocolNum or no claimable balance. string public constant VL_FLASHLOAN_FAILED = "127"; // Flashloan failed string public constant VL_ERC1155_NOT_TRANSFERABLE = "128"; // ERC1155: Not Transferable string public constant VL_SWAP_SLIPPAGE_LIMIT_EXCEED = "129"; // ERC1155: Not Transferable string public constant VL_ZERO_ADDR = "130"; // Zero Address string public constant MATH_DIVISION_BY_ZERO = "201"; string public constant MATH_ADDITION_OVERFLOW = "202"; string public constant MATH_MULTIPLICATION_OVERFLOW = "203"; string public constant RF_INVALID_RATIO_VALUES = "301"; // Ratio Value provided is invalid, _ratioA/_ratioB <= 1, and > 0, or activeProvider borrowBalance = 0 string public constant VLT_CALLER_MUST_BE_VAULT = "401"; // The caller of this function must be a vault string public constant ORACLE_INVALID_LENGTH = "501"; // The assets length and price feeds length doesn't match string public constant ORACLE_NONE_PRICE_FEED = "502"; // The price feed is not found } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155Upgradeable.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } }
Updates Index of AssetID _assetID: ERC1155 ID of the asset which state will be updated. newBalance: Amount/ TODO: calculate interest rate for a fujiOptimizer Fee.
function updateState(uint256 _assetID, uint256 newBalance) external override onlyPermit { uint256 total = totalSupply(_assetID); if (newBalance > 0 && total > 0 && newBalance > total) { uint256 diff = newBalance - total; uint256 amountToIndexRatio = (diff.wadToRay()).rayDiv(total.wadToRay()); uint256 result = amountToIndexRatio + WadRayMath.ray(); result = result.rayMul(indexes[_assetID]); require(result <= type(uint128).max, Errors.VL_INDEX_OVERFLOW); indexes[_assetID] = uint128(result); } }
13,405,699
pragma solidity 0.4.24; // File: zeppelin-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) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: zeppelin-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 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; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @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); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: zeppelin-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: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/ParkadeCoin.sol /** @title A dividend-paying ERC20 token, @dev Based on https://programtheblockchain.com/posts/2018/02/07/writing-a-simple-dividend-token-contract/ and https://programtheblockchain.com/posts/2018/02/13/writing-a-robust-dividend-token-contract/ */ contract ParkadeCoin is StandardToken, Ownable { using SafeMath for uint256; string public name = "Parkade Coin"; string public symbol = "PRKC"; uint8 public decimals = 18; /** There are a total of 400,000,000 tokens * 10^18 = 4 * 10^26 token units total A scaling value of 1e10 means that a deposit of 0.04Eth will increase scaledDividendPerToken by 1. A scaling value of 1e10 means that investors must wait until their scaledDividendBalances is at least 1e10 before any withdrawals will credit their account. */ uint256 public scaling = uint256(10) ** 10; // Remainder value (in Wei) resulting from deposits uint256 public scaledRemainder = 0; // Amount of wei credited to an account, but not yet withdrawn mapping(address => uint256) public scaledDividendBalances; // Cumulative amount of Wei credited to an account, since the contract's deployment mapping(address => uint256) public scaledDividendCreditedTo; // Cumulative amount of Wei that each token has been entitled to. Independent of withdrawals uint256 public scaledDividendPerToken = 0; /** * @dev Throws if transaction size is greater than the provided amount * This is used to mitigate the Ethereum short address attack as described in https://tinyurl.com/y8jjvh8d */ modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } constructor() public { // Total INITAL SUPPLY of 400 million tokens totalSupply_ = uint256(400000000) * (uint256(10) ** decimals); // Initially assign all tokens to the contract's creator. balances[msg.sender] = totalSupply_; emit Transfer(address(0), msg.sender, totalSupply_); } /** * @dev Update the dividend balances associated with an account * @param account The account address to update */ function update(address account) internal { // Calculate the amount "owed" to the account, in units of (wei / token) S // Subtract Wei already credited to the account (per token) from the total Wei per token uint256 owed = scaledDividendPerToken.sub(scaledDividendCreditedTo[account]); // Update the dividends owed to the account (in Wei) // # Tokens * (# Wei / token) = # Wei scaledDividendBalances[account] = scaledDividendBalances[account].add(balances[account].mul(owed)); // Update the total (wei / token) amount credited to the account scaledDividendCreditedTo[account] = scaledDividendPerToken; } event Transfer(address indexed from, address indexed to, uint256 value); event Deposit(uint256 value); event Withdraw(uint256 paidOut, address indexed to); mapping(address => mapping(address => uint256)) public allowance; /** * @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 onlyPayloadSize(2*32) returns (bool success) { require(balances[msg.sender] >= _value); // Added to transfer - update the dividend balances for both sender and receiver before transfer of tokens update(msg.sender); update(_to); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _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 onlyPayloadSize(3*32) returns (bool success) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); // Added to transferFrom - update the dividend balances for both sender and receiver before transfer of tokens update(_from); update(_to); 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 deposit Ether into the contract for dividend splitting */ function deposit() public payable onlyOwner { // Scale the deposit and add the previous remainder uint256 available = (msg.value.mul(scaling)).add(scaledRemainder); // Compute amount of Wei per token scaledDividendPerToken = scaledDividendPerToken.add(available.div(totalSupply_)); // Compute the new remainder scaledRemainder = available % totalSupply_; emit Deposit(msg.value); } /** * @dev withdraw dividends owed to an address */ function withdraw() public { // Update the dividend amount associated with the account update(msg.sender); // Compute amount owed to the investor uint256 amount = scaledDividendBalances[msg.sender].div(scaling); // Put back any remainder scaledDividendBalances[msg.sender] %= scaling; // Send investor the Wei dividends msg.sender.transfer(amount); emit Withdraw(amount, msg.sender); } } // File: zeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: zeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: zeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: zeppelin-solidity/contracts/crowdsale/distribution/utils/RefundVault.sol /** * @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); /** * @param _wallet Vault address */ function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } // File: zeppelin-solidity/contracts/crowdsale/distribution/RefundableCrowdsale.sol /** * @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 uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; /** * @dev Constructor, creates RefundVault. * @param _goal Funding goal */ function RefundableCrowdsale(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } } // File: zeppelin-solidity/contracts/crowdsale/validation/WhitelistedCrowdsale.sol /** * @title WhitelistedCrowdsale * @dev Crowdsale in which only whitelisted users can contribute. */ contract WhitelistedCrowdsale is Crowdsale, Ownable { mapping(address => bool) public whitelist; /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: contracts/ParkadeCoinCrowdsale.sol contract ParkadeCoinCrowdsale is TimedCrowdsale, RefundableCrowdsale, WhitelistedCrowdsale { // Discounted Rates. This is the amount of tokens (of the smallest possible denomination ie- 0.0000...0001PRKC) // that a user will receive per Wei contributed to the sale. uint256 public firstBonusRate = 1838; uint256 public secondBonusRate = 1634; uint256 public normalRate = 1470; // Timestamp indicating when the crowdsale will open // Aug 18, 2018 12:00:00 AM GMT uint256 public openingTime = 1534550400; // Timestamps indicating when the first and second bonus will end. // Aug 25, 2018 11:59:59PM GMT uint256 public firstBonusEnds = 1535155200; // Sep 8, 2018 11:59:59PM GMT uint256 public secondBonusEnds = 1536364800; // Timestamp indicating when the crowdsale will close // Sep 28, 2018 11:59:59PM GMT uint256 public closingTime = 1538179199; // A separate Ethereum address which only has the right to add addresses to the whitelist // It is not permitted to access any other functionality, or to claim funds // This is required for easier administration of the ParkadeCoin Crowdsale address public executor; // Whether refunds are allowed or not (regardless of if the tokensale's soft cap has been met) // This functionality allows Parkade.IO to refund all investors at the end of the tokensale, even if // the soft cap is not met. bool refundsAllowed; // Address where unsold tokens will be sent upon finalization of the sale address tokenTimelockContract; constructor ( uint256 _goal, address _owner, address _executor, address _tokenTimelockContract, StandardToken _token ) public Crowdsale(normalRate, _owner, _token) TimedCrowdsale(openingTime, closingTime) RefundableCrowdsale(_goal) { tokenTimelockContract = _tokenTimelockContract; executor = _executor; refundsAllowed = false; } /** * @dev Throws if called by any account other than the owner OR the executor. */ modifier onlyOwnerOrExecutor() { require(msg.sender == owner || msg.sender == executor); _; } /** * @dev Public function that allows users to determine the current price (in wei) per token * @return Current price per token in wei */ function currentRate() public view returns (uint256) { if (block.timestamp < firstBonusEnds) { return firstBonusRate; } else if (block.timestamp >= firstBonusEnds && block.timestamp < secondBonusEnds) { return secondBonusRate; } else { return normalRate; } } /** * @dev Function to change the contract's executor, which can then add addresses to the whitelist * @param _newExec Address of new executor */ function changeExecutor(address _newExec) external onlyOwnerOrExecutor { require(_newExec != address(0)); executor = _newExec; } /** * @dev Overriden token value function. Provides functionality for discounted rates in the tokensale * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(currentRate()); } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwnerOrExecutor { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwnerOrExecutor { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwnerOrExecutor { whitelist[_beneficiary] = false; } /** * @dev Validation of an incoming purchase. Overridden to ensure that the tokensale contains enough tokens to sell. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(token.balanceOf(this) > _getTokenAmount(_weiAmount)); super._preValidatePurchase(_beneficiary, _weiAmount); } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful (softcap not reached or as specified by owner) */ function claimRefund() public { // Cannot refund before tokensale is finished require(hasClosed()); // If the goal has been reached, then double-check that refunds are allowed by owner's override if (goalReached()) { require(refundsAllowed); } vault.refund(msg.sender); } /** * @dev Allow the tokensale owner to specify that refunds are allowed regardless of soft cap goal */ function allowRefunds() external onlyOwner { require(!isFinalized); require(hasClosed()); refundsAllowed = true; vault.enableRefunds(); } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { require(!refundsAllowed); // Send all unsold tokens to the Timelock contract for future vesting token.transfer(tokenTimelockContract, token.balanceOf(this)); super.finalization(); } }
investor Investor address/
function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); }
98,330
./full_match/1/0xe63E8226095C7AE90D1e46636740d8A9998AD191/sources/contracts/facets/MethodsExposureFacet.sol
Returns the account approved for `tokenId` token. Requirements: - `tokenId` must exist./
function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data function safeTransferFrom( address from, address to, uint256 tokenId function transferFrom( address from, address to, uint256 tokenId function getApproved(uint256 tokenId) external view returns (address operator) { return address(0); }
3,029,098
./partial_match/1/0x19C452E317100A8cAF5573d37a1711FFa89cbe71/sources/HabaneroFarmField.sol
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "HABANERO::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
4,459,658
/** *Submitted for verification at Etherscan.io on 2020-10-17 */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.6; /** * @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 (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); } // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @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(uint a, uint b) internal pure returns (uint) { uint c = a + b; //require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "TimeLoans::SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ 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, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint a, uint b) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, errorMessage); 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(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. * 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(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; // 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(uint a, uint b) internal pure returns (uint) { 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(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b != 0, errorMessage); return a % b; } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapOracleRouter { function quote(address tokenIn, address tokenOut, uint amountIn) external view returns (uint amountOut); } contract TimeLoanPair { using SafeMath for uint; /// @notice EIP-20 token name for this token string public constant name = "Time Loan Pair LP"; /// @notice EIP-20 token symbol for this token string public symbol; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 0; // Initial 0 mapping (address => mapping (address => uint)) internal allowances; mapping (address => uint) internal balances; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint amount); /// @notice Uniswap V2 Router used for all swaps and liquidity management IUniswapV2Router02 public constant UNI = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); /// @notice Uniswap Oracle Router used for all 24 hour TWAP price metrics IUniswapOracleRouter public constant ORACLE = IUniswapOracleRouter(0x0b5A6b318c39b60e7D8462F888e7fbA89f75D02F); /// @notice The underlying Uniswap Pair used for loan liquidity address public pair; /// @notice The token0 of the Uniswap Pair address public token0; /// @notice The token1 of the Uniswap Pair address public token1; /// @notice Deposited event for creditor/LP event Deposited(address indexed creditor, address indexed collateral, uint shares, uint credit); /// @notice Withdawn event for creditor/LP event Withdrew(address indexed creditor, address indexed collateral, uint shares, uint credit); /// @notice The borrow event for any borrower event Borrowed(uint id, address indexed borrower, address indexed collateral, address indexed borrowed, uint creditIn, uint amountOut, uint created, uint expire); /// @notice The close loan event when processing expired loans event Repaid(uint id, address indexed borrower, address indexed collateral, address indexed borrowed, uint creditIn, uint amountOut, uint created, uint expire); /// @notice The close loan event when processing expired loans event Closed(uint id, address indexed borrower, address indexed collateral, address indexed borrowed, uint creditIn, uint amountOut, uint created, uint expire); /// @notice 0.6% initiation fee for all loans uint public constant FEE = 600; // 0.6% loan initiation fee /// @notice 105% liquidity buffer on withdrawing liquidity uint public constant BUFFER = 105000; // 105% liquidity buffer /// @notice 80% loan to value ratio uint public constant LTV = 80000; // 80% loan to value ratio /// @notice base for all % based calculations uint public constant BASE = 100000; /// @notice the delay for a position to be closed uint public constant DELAY = 6600; // ~24 hours till position is closed struct position { address owner; address collateral; address borrowed; uint creditIn; uint amountOut; uint liquidityInUse; uint created; uint expire; bool open; } /// @notice array of all loan positions position[] public positions; /// @notice the tip index of the positions array uint public nextIndex; /// @notice the last index processed by the contract uint public processedIndex; /// @notice mapping of loans assigned to users mapping(address => uint[]) public loans; /// @notice constructor takes a uniswap pair as an argument to set its 2 borrowable assets constructor(IUniswapV2Pair _pair) public { symbol = string(abi.encodePacked(IUniswapV2Pair(_pair.token0()).symbol(), "-", IUniswapV2Pair(_pair.token1()).symbol())); pair = address(_pair); token0 = _pair.token0(); token1 = _pair.token1(); } /// @notice total liquidity deposited uint public liquidityDeposits; /// @notice total liquidity withdrawn uint public liquidityWithdrawals; /// @notice total liquidity added via addLiquidity uint public liquidityAdded; /// @notice total liquidity removed via removeLiquidity uint public liquidityRemoved; /// @notice total liquidity currently in use by pending loans uint public liquidityInUse; /// @notice total liquidity freed up from closed loans uint public liquidityFreed; /** * @notice the current net liquidity positions * @return the net liquidity sum */ function liquidityBalance() public view returns (uint) { return liquidityDeposits .sub(liquidityWithdrawals) .add(liquidityAdded) .sub(liquidityRemoved) .add(liquidityInUse) .sub(liquidityFreed); } function _mint(address dst, uint amount) internal { // mint the amount totalSupply = totalSupply.add(amount); // transfer the amount to the recipient balances[dst] = balances[dst].add(amount); emit Transfer(address(0), dst, amount); } function _burn(address dst, uint amount) internal { // burn the amount totalSupply = totalSupply.sub(amount, "TimeLoans::_burn: underflow"); // transfer the amount to the recipient balances[dst] = balances[dst].sub(amount, "TimeLoans::_burn: underflow"); emit Transfer(dst, address(0), amount); } /** * @notice withdraw all liquidity from msg.sender shares * @return success/failure */ function withdrawAll() external returns (bool) { return withdraw(balances[msg.sender]); } /** * @notice withdraw `_shares` amount of liquidity for user * @param _shares the amount of shares to burn for liquidity * @return success/failure */ function withdraw(uint _shares) public returns (bool) { uint r = liquidityBalance().mul(_shares).div(totalSupply); _burn(msg.sender, _shares); require(IERC20(pair).balanceOf(address(this)) > r, "TimeLoans::withdraw: insufficient liquidity to withdraw, try depositLiquidity()"); IERC20(pair).transfer(msg.sender, r); liquidityWithdrawals = liquidityWithdrawals.add(r); emit Withdrew(msg.sender, pair, _shares, r); return true; } /** * @notice deposit all liquidity from msg.sender * @return success/failure */ function depositAll() external returns (bool) { return deposit(IERC20(pair).balanceOf(msg.sender)); } /** * @notice deposit `amount` amount of liquidity for user * @param amount the amount of liquidity to add for shares * @return success/failure */ function deposit(uint amount) public returns (bool) { IERC20(pair).transferFrom(msg.sender, address(this), amount); uint _shares = 0; if (liquidityBalance() == 0) { _shares = amount; } else { _shares = amount.mul(totalSupply).div(liquidityBalance()); } _mint(msg.sender, _shares); liquidityDeposits = liquidityDeposits.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Deposited(msg.sender, pair, _shares, amount); return true; } /** * @notice batch close any pending open loans that have expired * @param size the maximum size of batch to execute * @return the last index processed */ function closeInBatches(uint size) external returns (uint) { uint i = processedIndex; for (; i < size; i++) { close(i); } processedIndex = i; return processedIndex; } /** * @notice iterate through all open loans and close * @return the last index processed */ function closeAllOpen() external returns (uint) { uint i = processedIndex; for (; i < nextIndex; i++) { close(i); } processedIndex = i; return processedIndex; } /** * @notice close a specific loan based on id * @param id the `id` of the given loan to close * @return success/failure */ function close(uint id) public returns (bool) { position storage _pos = positions[id]; if (_pos.owner == address(0x0)) { return false; } if (!_pos.open) { return false; } if (_pos.expire < block.number) { return false; } _pos.open = false; liquidityInUse = liquidityInUse.sub(_pos.liquidityInUse, "TimeLoans::close: liquidityInUse overflow"); liquidityFreed = liquidityFreed.add(_pos.liquidityInUse); emit Closed(id, _pos.owner, _pos.collateral, _pos.borrowed, _pos.creditIn, _pos.amountOut, _pos.created, _pos.expire); return true; } /** * @notice returns the available liquidity (including LP tokens) for a given asset * @param asset the asset to calculate liquidity for * @return the amount of liquidity available */ function liquidityOf(address asset) public view returns (uint) { return IERC20(asset).balanceOf(address(this)). add(IERC20(asset).balanceOf(pair) .mul(IERC20(pair).balanceOf(address(this))) .div(IERC20(pair).totalSupply())); } /** * @notice calculates the amount of liquidity to burn to get the amount of asset * @param amount the amount of asset required as output * @return the amount of liquidity to burn */ function calculateLiquidityToBurn(address asset, uint amount) public view returns (uint) { return IERC20(pair).balanceOf(address(this)) .mul(amount) .div(IERC20(asset).balanceOf(pair)); } /** * @notice withdraw liquidity to get the amount of tokens required to borrow * @param asset the asset output required * @param amount the amount of asset required as output */ function _withdrawLiquidity(address asset, uint amount) internal returns (uint withdrew) { withdrew = calculateLiquidityToBurn(asset, amount); withdrew = withdrew.mul(BUFFER).div(BASE); uint _amountAMin = 0; uint _amountBMin = 0; if (asset == token0) { _amountAMin = amount; } else if (asset == token1) { _amountBMin = amount; } IERC20(pair).approve(address(UNI), withdrew); UNI.removeLiquidity(token0, token1, withdrew, _amountAMin, _amountBMin, address(this), now.add(1800)); liquidityRemoved = liquidityRemoved.add(withdrew); } /** * @notice Provides a quote of how much output can be expected given the inputs * @param collateral the asset being used as collateral * @param borrow the asset being borrowed * @param amount the amount of collateral being provided * @return minOut the minimum amount of liquidity to borrow */ function quote(address collateral, address borrow, uint amount) external view returns (uint minOut) { uint _received = (amount.sub(amount.mul(FEE).div(BASE))).mul(LTV).div(BASE); return ORACLE.quote(collateral, borrow, _received); } /** * @notice deposit available liquidity in the system into the Uniswap Pair, manual for now, require keepers in later iterations */ function depositLiquidity() external { require(msg.sender == tx.origin, "TimeLoans::depositLiquidity: not an EOA keeper"); IERC20(token0).approve(address(UNI), IERC20(token0).balanceOf(address(this))); IERC20(token1).approve(address(UNI), IERC20(token1).balanceOf(address(this))); (,,uint _added) = UNI.addLiquidity(token0, token1, IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), 0, 0, address(this), now.add(1800)); liquidityAdded = liquidityAdded.add(_added); } /** * @notice Returns greater than `outMin` amount of `borrow` based on `amount` of `collateral supplied * @param collateral the asset being used as collateral * @param borrow the asset being borrowed * @param amount the amount of collateral being provided * @param outMin the minimum amount of liquidity to borrow */ function loan(address collateral, address borrow, uint amount, uint outMin) external returns (uint) { uint _before = IERC20(collateral).balanceOf(address(this)); IERC20(collateral).transferFrom(msg.sender, address(this), amount); uint _after = IERC20(collateral).balanceOf(address(this)); uint _received = _after.sub(_before); uint _fee = _received.mul(FEE).div(BASE); _received = _received.sub(_fee); uint _ltv = _received.mul(LTV).div(BASE); uint _amountOut = ORACLE.quote(collateral, borrow, _ltv); require(_amountOut >= outMin, "TimeLoans::loan: slippage"); require(liquidityOf(borrow) > _amountOut, "TimeLoans::loan: insufficient liquidity"); uint _available = IERC20(borrow).balanceOf(address(this)); uint _withdrew = 0; if (_available < _amountOut) { _withdrew = _withdrawLiquidity(borrow, _amountOut.sub(_available)); liquidityInUse = liquidityInUse.add(_withdrew); } positions.push(position(msg.sender, collateral, borrow, _received, _amountOut, _withdrew, block.number, block.number.add(DELAY), true)); loans[msg.sender].push(nextIndex); IERC20(borrow).transfer(msg.sender, _amountOut); emit Borrowed(nextIndex, msg.sender, collateral, borrow, _received, _amountOut, block.number, block.number.add(DELAY)); return nextIndex++; } /** * @notice Repay a pending loan with `id` anyone can repay, no owner check * @param id the id of the loan to close * @return true/false if loan was successfully closed */ function repay(uint id) external returns (bool) { position storage _pos = positions[id]; require(_pos.open, "TimeLoans::repay: position is already closed"); require(_pos.expire < block.number, "TimeLoans::repay: position already expired"); IERC20(_pos.borrowed).transferFrom(msg.sender, address(this), _pos.amountOut); uint _available = IERC20(_pos.collateral).balanceOf(address(this)); if (_available < _pos.creditIn) { _withdrawLiquidity(_pos.collateral, _pos.creditIn.sub(_available)); } IERC20(_pos.collateral).transfer(msg.sender, _pos.creditIn); _pos.open = false; positions[id] = _pos; emit Repaid(id, _pos.owner, _pos.collateral, _pos.borrowed, _pos.creditIn, _pos.amountOut, _pos.created, _pos.expire); return true; } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint amount) public returns (bool) { 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 amount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint amount, uint deadline, 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(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "TimeLoans::permit: invalid signature"); require(signatory == owner, "TimeLoans::permit: unauthorized"); require(now <= deadline, "TimeLoans::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) public returns (bool) { _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 amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint amount) external returns (bool) { address spender = msg.sender; uint spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint(-1)) { uint newAllowance = spenderAllowance.sub(amount, "TimeLoans::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function _transferTokens(address src, address dst, uint amount) internal { require(src != address(0), "TimeLoans::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "TimeLoans::_transferTokens: cannot transfer to the zero address"); balances[src] = balances[src].sub(amount, "TimeLoans::_transferTokens: transfer amount exceeds balance"); balances[dst] = balances[dst].add(amount, "TimeLoans::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); } function getChainId() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } } contract TimeLoanPairFactory { mapping(address => address) pairs; function deploy(IUniswapV2Pair _pair) external { require(pairs[address(_pair)] == address(0x0), "TimeLoanPairFactory::deploy: pair already created"); pairs[address(_pair)] = address(new TimeLoanPair(_pair)); } }
Returns the addition of two unsigned integers, reverting on overflow. Counterpart to Solidity's `+` operator. Requirements: - Addition cannot overflow./require(c >= a, "SafeMath: addition overflow");
function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; return c; }
7,323,951
pragma solidity ^0.4.23; // ---------------------------------------------------------------------------- // ERC20Interface - Standard ERC20 Interface Definition // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Based on the final ERC20 specification at: // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function name() public view returns (string); function symbol() public view returns (string); function decimals() public view returns (uint8); function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256 balance); function allowance(address _owner, address _spender) public view returns (uint256 remaining); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); } // ---------------------------------------------------------------------------- // Math - General Math Utility Library // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- library Math { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 r = a + b; require(r >= a); return r; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b); return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 r = a * b; require(r / a == b); return r; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } } // ---------------------------------------------------------------------------- // Owned - Ownership model with 2 phase transfers // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- // Implements a simple ownership model with 2-phase transfer. contract Owned { address public owner; address public proposedOwner; event OwnershipTransferInitiated(address indexed _proposedOwner); event OwnershipTransferCompleted(address indexed _newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(isOwner(msg.sender) == true); _; } function isOwner(address _address) public view returns (bool) { return (_address == owner); } function initiateOwnershipTransfer(address _proposedOwner) public onlyOwner returns (bool) { require(_proposedOwner != address(0)); require(_proposedOwner != address(this)); require(_proposedOwner != owner); proposedOwner = _proposedOwner; emit OwnershipTransferInitiated(proposedOwner); return true; } function completeOwnershipTransfer() public returns (bool) { require(msg.sender == proposedOwner); owner = msg.sender; proposedOwner = address(0); emit OwnershipTransferCompleted(owner); return true; } } // ---------------------------------------------------------------------------- // Finalizable - Basic implementation of the finalization pattern // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- contract Finalizable is Owned() { bool public finalized; event Finalized(); constructor() public { finalized = false; } function finalize() public onlyOwner returns (bool) { require(!finalized); finalized = true; emit Finalized(); return true; } } // ---------------------------------------------------------------------------- // OpsManaged - Implements an Owner and Ops Permission Model // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- // // Implements a security model with owner and ops. // contract OpsManaged is Owned() { address public opsAddress; event OpsAddressUpdated(address indexed _newAddress); constructor() public { } modifier onlyOwnerOrOps() { require(isOwnerOrOps(msg.sender)); _; } function isOps(address _address) public view returns (bool) { return (opsAddress != address(0) && _address == opsAddress); } function isOwnerOrOps(address _address) public view returns (bool) { return (isOwner(_address) || isOps(_address)); } function setOpsAddress(address _newOpsAddress) public onlyOwner returns (bool) { require(_newOpsAddress != owner); require(_newOpsAddress != address(this)); opsAddress = _newOpsAddress; emit OpsAddressUpdated(opsAddress); return true; } } // ---------------------------------------------------------------------------- // ERC20Token - Standard ERC20 Implementation // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- contract ERC20Token is ERC20Interface { using Math for uint256; string private tokenName; string private tokenSymbol; uint8 private tokenDecimals; uint256 internal tokenTotalSupply; mapping(address => uint256) internal balances; mapping(address => mapping (address => uint256)) allowed; constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply, address _initialTokenHolder) public { tokenName = _name; tokenSymbol = _symbol; tokenDecimals = _decimals; tokenTotalSupply = _totalSupply; // The initial balance of tokens is assigned to the given token holder address. balances[_initialTokenHolder] = _totalSupply; // Per EIP20, the constructor should fire a Transfer event if tokens are assigned to an account. emit Transfer(0x0, _initialTokenHolder, _totalSupply); } function name() public view returns (string) { return tokenName; } function symbol() public view returns (string) { return tokenSymbol; } function decimals() public view returns (uint8) { return tokenDecimals; } function totalSupply() public view returns (uint256) { return tokenTotalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } function transfer(address _to, uint256 _value) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } } // ---------------------------------------------------------------------------- // FinalizableToken - Extension to ERC20Token with ops and finalization // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- // // ERC20 token with the following additions: // 1. Owner/Ops Ownership // 2. Finalization // contract FinalizableToken is ERC20Token, OpsManaged, Finalizable { using Math for uint256; // The constructor will assign the initial token supply to the owner (msg.sender). constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public ERC20Token(_name, _symbol, _decimals, _totalSupply, msg.sender) OpsManaged() Finalizable() { } function transfer(address _to, uint256 _value) public returns (bool success) { validateTransfer(msg.sender, _to); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { validateTransfer(msg.sender, _to); return super.transferFrom(_from, _to, _value); } function validateTransfer(address _sender, address _to) private view { // Once the token is finalized, everybody can transfer tokens. if (finalized) { return; } if (isOwner(_to)) { return; } // Before the token is finalized, only owner and ops are allowed to initiate transfers. // This allows them to move tokens while the sale is still ongoing for example. require(isOwnerOrOps(_sender)); } } // ---------------------------------------------------------------------------- // FlexibleTokenSale - Token Sale Contract // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- contract FlexibleTokenSale is Finalizable, OpsManaged { using Math for uint256; // // Lifecycle // uint256 public startTime; uint256 public endTime; bool public suspended; // // Pricing // uint256 public tokensPerKEther; uint256 public bonus; uint256 public maxTokensPerAccount; uint256 public contributionMin; uint256 public tokenConversionFactor; // // Wallets // address public walletAddress; // // Token // FinalizableToken public token; // // Counters // uint256 public totalTokensSold; uint256 public totalEtherCollected; // // Events // event Initialized(); event TokensPerKEtherUpdated(uint256 _newValue); event MaxTokensPerAccountUpdated(uint256 _newMax); event BonusUpdated(uint256 _newValue); event SaleWindowUpdated(uint256 _startTime, uint256 _endTime); event WalletAddressUpdated(address _newAddress); event SaleSuspended(); event SaleResumed(); event TokensPurchased(address _beneficiary, uint256 _cost, uint256 _tokens); event TokensReclaimed(uint256 _amount); constructor(uint256 _startTime, uint256 _endTime, address _walletAddress) public OpsManaged() { require(_endTime > _startTime); require(_walletAddress != address(0)); require(_walletAddress != address(this)); walletAddress = _walletAddress; finalized = false; suspended = false; startTime = _startTime; endTime = _endTime; // Use some defaults config values. Classes deriving from FlexibleTokenSale // should set their own defaults tokensPerKEther = 100000; bonus = 0; maxTokensPerAccount = 0; contributionMin = 0.1 ether; totalTokensSold = 0; totalEtherCollected = 0; } function currentTime() public constant returns (uint256) { return now; } // Initialize should be called by the owner as part of the deployment + setup phase. // It will associate the sale contract with the token contract and perform basic checks. function initialize(FinalizableToken _token) external onlyOwner returns(bool) { require(address(token) == address(0)); require(address(_token) != address(0)); require(address(_token) != address(this)); require(address(_token) != address(walletAddress)); require(isOwnerOrOps(address(_token)) == false); token = _token; // This factor is used when converting cost <-> tokens. // 18 is because of the ETH -> Wei conversion. // 3 because prices are in K ETH instead of just ETH. // 4 because bonuses are expressed as 0 - 10000 for 0.00% - 100.00% (with 2 decimals). tokenConversionFactor = 10**(uint256(18).sub(_token.decimals()).add(3).add(4)); require(tokenConversionFactor > 0); emit Initialized(); return true; } // // Owner Configuation // // Allows the owner to change the wallet address which is used for collecting // ether received during the token sale. function setWalletAddress(address _walletAddress) external onlyOwner returns(bool) { require(_walletAddress != address(0)); require(_walletAddress != address(this)); require(_walletAddress != address(token)); require(isOwnerOrOps(_walletAddress) == false); walletAddress = _walletAddress; emit WalletAddressUpdated(_walletAddress); return true; } // Allows the owner to set an optional limit on the amount of tokens that can be purchased // by a contributor. It can also be set to 0 to remove limit. function setMaxTokensPerAccount(uint256 _maxTokens) external onlyOwner returns(bool) { maxTokensPerAccount = _maxTokens; emit MaxTokensPerAccountUpdated(_maxTokens); return true; } // Allows the owner to specify the conversion rate for ETH -> tokens. // For example, passing 1,000,000 would mean that 1 ETH would purchase 1000 tokens. function setTokensPerKEther(uint256 _tokensPerKEther) external onlyOwner returns(bool) { require(_tokensPerKEther > 0); tokensPerKEther = _tokensPerKEther; emit TokensPerKEtherUpdated(_tokensPerKEther); return true; } // Allows the owner to set a bonus to apply to all purchases. // For example, setting it to 2000 means that instead of receiving 200 tokens, // for a given price, contributors would receive 240 tokens (20.00% bonus). function setBonus(uint256 _bonus) external onlyOwner returns(bool) { require(_bonus <= 10000); bonus = _bonus; emit BonusUpdated(_bonus); return true; } // Allows the owner to set a sale window which will allow the sale (aka buyTokens) to // receive contributions between _startTime and _endTime. Once _endTime is reached, // the sale contract will automatically stop accepting incoming contributions. function setSaleWindow(uint256 _startTime, uint256 _endTime) external onlyOwner returns(bool) { require(_startTime > 0); require(_endTime > _startTime); startTime = _startTime; endTime = _endTime; emit SaleWindowUpdated(_startTime, _endTime); return true; } // Allows the owner to suspend the sale until it is manually resumed at a later time. function suspend() external onlyOwner returns(bool) { if (suspended == true) { return false; } suspended = true; emit SaleSuspended(); return true; } // Allows the owner to resume the sale. function resume() external onlyOwner returns(bool) { if (suspended == false) { return false; } suspended = false; emit SaleResumed(); return true; } // // Contributions // // Default payable function which can be used to purchase tokens. function () payable public { buyTokens(msg.sender); } // Allows the caller to purchase tokens for a specific beneficiary (proxy purchase). function buyTokens(address _beneficiary) public payable returns (uint256) { return buyTokensInternal(_beneficiary, bonus); } function buyTokensInternal(address _beneficiary, uint256 _bonus) internal returns (uint256) { require(!finalized); require(!suspended); require(currentTime() >= startTime); require(currentTime() <= endTime); require(msg.value >= contributionMin); require(_beneficiary != address(0)); require(_beneficiary != address(this)); require(_beneficiary != address(token)); // We don't want to allow the wallet collecting ETH to // directly be used to purchase tokens. require(msg.sender != address(walletAddress)); // Check how many tokens are still available for sale. uint256 saleBalance = token.balanceOf(address(this)); require(saleBalance > 0); // Calculate how many tokens the contributor could purchase based on ETH received. uint256 tokens = msg.value.mul(tokensPerKEther).mul(_bonus.add(10000)).div(tokenConversionFactor); require(tokens > 0); uint256 cost = msg.value; uint256 refund = 0; // Calculate what is the maximum amount of tokens that the contributor // should be allowed to purchase uint256 maxTokens = saleBalance; if (maxTokensPerAccount > 0) { // There is a maximum amount of tokens per account in place. // Check if the user already hit that limit. uint256 userBalance = getUserTokenBalance(_beneficiary); require(userBalance < maxTokensPerAccount); uint256 quotaBalance = maxTokensPerAccount.sub(userBalance); if (quotaBalance < saleBalance) { maxTokens = quotaBalance; } } require(maxTokens > 0); if (tokens > maxTokens) { // The contributor sent more ETH than allowed to purchase. // Limit the amount of tokens that they can purchase in this transaction. tokens = maxTokens; // Calculate the actual cost for that new amount of tokens. cost = tokens.mul(tokenConversionFactor).div(tokensPerKEther.mul(_bonus.add(10000))); if (msg.value > cost) { // If the contributor sent more ETH than needed to buy the tokens, // the balance should be refunded. refund = msg.value.sub(cost); } } // This is the actual amount of ETH that can be sent to the wallet. uint256 contribution = msg.value.sub(refund); walletAddress.transfer(contribution); // Update our stats counters. totalTokensSold = totalTokensSold.add(tokens); totalEtherCollected = totalEtherCollected.add(contribution); // Transfer tokens to the beneficiary. require(token.transfer(_beneficiary, tokens)); // Issue a refund for the excess ETH, as needed. if (refund > 0) { msg.sender.transfer(refund); } emit TokensPurchased(_beneficiary, cost, tokens); return tokens; } // Returns the number of tokens that the user has purchased. Will be checked against the // maximum allowed. Can be overriden in a sub class to change the calculations. function getUserTokenBalance(address _beneficiary) internal view returns (uint256) { return token.balanceOf(_beneficiary); } // Allows the owner to take back the tokens that are assigned to the sale contract. function reclaimTokens() external onlyOwner returns (bool) { uint256 tokens = token.balanceOf(address(this)); if (tokens == 0) { return false; } address tokenOwner = token.owner(); require(tokenOwner != address(0)); require(token.transfer(tokenOwner, tokens)); emit TokensReclaimed(tokens); return true; } } // ---------------------------------------------------------------------------- // CaspianTokenConfig - Token Contract Configuration // // Copyright (c) 2018 Caspian, Limited (TM). // http://www.caspian.tech/ // ---------------------------------------------------------------------------- contract CaspianTokenConfig { string public constant TOKEN_SYMBOL = "CSP"; string public constant TOKEN_NAME = "Caspian Token"; uint8 public constant TOKEN_DECIMALS = 18; uint256 public constant DECIMALSFACTOR = 10**uint256(TOKEN_DECIMALS); uint256 public constant TOKEN_TOTALSUPPLY = 1000000000 * DECIMALSFACTOR; } // ---------------------------------------------------------------------------- // CaspianTokenSaleConfig - Token Sale Configuration // // Copyright (c) 2018 Caspian, Limited (TM). // http://www.caspian.tech/ // ---------------------------------------------------------------------------- contract CaspianTokenSaleConfig is CaspianTokenConfig { // // Time // uint256 public constant INITIAL_STARTTIME = 1538553600; // 2018-10-03, 08:00:00 UTC uint256 public constant INITIAL_ENDTIME = 1538726400; // 2018-10-05, 08:00:00 UTC // // Purchases // // Minimum amount of ETH that can be used for purchase. uint256 public constant CONTRIBUTION_MIN = 0.5 ether; // Price of tokens, based on the 1 ETH = 4000 CSP conversion ratio. uint256 public constant TOKENS_PER_KETHER = 4000000; // Amount of bonus applied to the sale. 2000 = 20.00% bonus, 750 = 7.50% bonus, 0 = no bonus. uint256 public constant BONUS = 0; // Maximum amount of tokens that can be purchased for each account. 0 for no maximum. uint256 public constant TOKENS_ACCOUNT_MAX = 400000 * DECIMALSFACTOR; // 100 ETH Max } // ---------------------------------------------------------------------------- // CaspianTokenSale - Token Sale Contract // // Copyright (c) 2018 Caspian, Limited (TM). // http://www.caspian.tech/ // // Based on code from Enuma Technologies. // Copyright (c) 2017 Enuma Technologies Limited. // ---------------------------------------------------------------------------- contract CaspianTokenSale is FlexibleTokenSale, CaspianTokenSaleConfig { // // Whitelist // uint8 public currentPhase; mapping(address => uint8) public whitelist; // // Events // event WhitelistUpdated(address indexed _account, uint8 _phase); constructor(address wallet) public FlexibleTokenSale(INITIAL_STARTTIME, INITIAL_ENDTIME, wallet) { tokensPerKEther = TOKENS_PER_KETHER; bonus = BONUS; maxTokensPerAccount = TOKENS_ACCOUNT_MAX; contributionMin = CONTRIBUTION_MIN; currentPhase = 1; } // Allows the owner or ops to add/remove people from the whitelist. function updateWhitelist(address _address, uint8 _phase) external onlyOwnerOrOps returns (bool) { return updateWhitelistInternal(_address, _phase); } function updateWhitelistInternal(address _address, uint8 _phase) internal returns (bool) { require(_address != address(0)); require(_address != address(this)); require(_address != walletAddress); require(_phase <= 1); whitelist[_address] = _phase; emit WhitelistUpdated(_address, _phase); return true; } // Allows the owner or ops to add/remove people from the whitelist, in batches. function updateWhitelistBatch(address[] _addresses, uint8 _phase) external onlyOwnerOrOps returns (bool) { require(_addresses.length > 0); for (uint256 i = 0; i < _addresses.length; i++) { require(updateWhitelistInternal(_addresses[i], _phase)); } return true; } // This is an extension to the buyToken function in FlexibleTokenSale which also takes // care of checking contributors against the whitelist. Since buyTokens supports proxy payments // we check that both the sender and the beneficiary have been whitelisted. function buyTokensInternal(address _beneficiary, uint256 _bonus) internal returns (uint256) { require(whitelist[msg.sender] >= currentPhase); require(whitelist[_beneficiary] >= currentPhase); return super.buyTokensInternal(_beneficiary, _bonus); } }
Allows the owner to set an optional limit on the amount of tokens that can be purchased by a contributor. It can also be set to 0 to remove limit.
function setMaxTokensPerAccount(uint256 _maxTokens) external onlyOwner returns(bool) { maxTokensPerAccount = _maxTokens; emit MaxTokensPerAccountUpdated(_maxTokens); return true; }
14,515,408
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {IBNFT} from "../interfaces/IBNFT.sol"; import {IFlashLoanReceiver} from "../interfaces/IFlashLoanReceiver.sol"; import {StringsUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import {AddressUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import {ERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import {ERC721EnumerableUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {IERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import {IERC1155Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import {IERC721MetadataUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; import {IERC721ReceiverUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import {IERC1155ReceiverUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; /** * @title BNFT contract * @dev Implements the methods for the bNFT protocol **/ contract BNFT is IBNFT, ERC721EnumerableUpgradeable, IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { address private _underlyingAsset; // Mapping from token ID to minter address mapping(uint256 => address) private _minters; address private _owner; uint256 private constant _NOT_ENTERED = 0; uint256 private constant _ENTERED = 1; uint256 private _status; /** * @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; } /** * @dev Initializes the bNFT * @param underlyingAsset_ The address of the underlying asset of this bNFT (E.g. PUNK for bPUNK) */ function initialize( address underlyingAsset_, string calldata bNftName, string calldata bNftSymbol, address owner_ ) external override initializer { __ERC721_init(bNftName, bNftSymbol); _underlyingAsset = underlyingAsset_; _transferOwnership(owner_); emit Initialized(underlyingAsset_); } /** * @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(), "BNFT: 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), "BNFT: 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); } /** * @dev Mints bNFT token to the user address * * Requirements: * - The caller can be contract address and EOA * * @param to The owner address receive the bNFT token * @param tokenId token id of the underlying asset of NFT **/ function mint(address to, uint256 tokenId) external override nonReentrant { bool isCA = AddressUpgradeable.isContract(_msgSender()); if (!isCA) { require(to == _msgSender(), "BNFT: caller is not to"); } require(!_exists(tokenId), "BNFT: exist token"); require(IERC721Upgradeable(_underlyingAsset).ownerOf(tokenId) == _msgSender(), "BNFT: caller is not owner"); // Receive NFT Tokens IERC721Upgradeable(_underlyingAsset).safeTransferFrom(_msgSender(), address(this), tokenId); // mint bNFT to user _mint(to, tokenId); _minters[tokenId] = _msgSender(); emit Mint(_msgSender(), _underlyingAsset, tokenId, to); } /** * @dev Burns user bNFT token * * Requirements: * - The caller can be contract address and EOA * * @param tokenId token id of the underlying asset of NFT **/ function burn(uint256 tokenId) external override nonReentrant { require(_exists(tokenId), "BNFT: nonexist token"); require(_minters[tokenId] == _msgSender(), "BNFT: caller is not minter"); address tokenOwner = ERC721Upgradeable.ownerOf(tokenId); IERC721Upgradeable(_underlyingAsset).safeTransferFrom(address(this), _msgSender(), tokenId); _burn(tokenId); delete _minters[tokenId]; emit Burn(_msgSender(), _underlyingAsset, tokenId, tokenOwner); } /** * @dev See {IBNFT-flashLoan}. */ function flashLoan( address receiverAddress, uint256[] calldata nftTokenIds, bytes calldata params ) external override nonReentrant { uint256 i; IFlashLoanReceiver receiver = IFlashLoanReceiver(receiverAddress); // !!!CAUTION: receiver contract may reentry mint, burn, flashloan again require(receiverAddress != address(0), "BNFT: zero address"); require(nftTokenIds.length > 0, "BNFT: empty token list"); // only token owner can do flashloan for (i = 0; i < nftTokenIds.length; i++) { require(ownerOf(nftTokenIds[i]) == _msgSender(), "BNFT: caller is not owner"); } // step 1: moving underlying asset forward to receiver contract for (i = 0; i < nftTokenIds.length; i++) { IERC721Upgradeable(_underlyingAsset).safeTransferFrom(address(this), receiverAddress, nftTokenIds[i]); } // setup 2: execute receiver contract, doing something like aidrop require( receiver.executeOperation(_underlyingAsset, nftTokenIds, _msgSender(), address(this), params), "BNFT: invalid flashloan executor return" ); // setup 3: moving underlying asset backword from receiver contract for (i = 0; i < nftTokenIds.length; i++) { IERC721Upgradeable(_underlyingAsset).safeTransferFrom(receiverAddress, address(this), nftTokenIds[i]); emit FlashLoan(receiverAddress, _msgSender(), _underlyingAsset, nftTokenIds[i]); } } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { return IERC721MetadataUpgradeable(_underlyingAsset).tokenURI(tokenId); } /** * @dev See {IBNFT-contractURI}. */ function contractURI() external view override returns (string memory) { string memory hexAddress = StringsUpgradeable.toHexString(uint256(uint160(address(this))), 20); return string(abi.encodePacked("https://metadata.benddao.xyz/", hexAddress)); } function claimERC20Airdrop( address token, address to, uint256 amount ) external override nonReentrant onlyOwner { require(token != _underlyingAsset, "BNFT: token can not be underlying asset"); require(token != address(this), "BNFT: token can not be self address"); IERC20Upgradeable(token).transfer(to, amount); emit ClaimERC20Airdrop(token, to, amount); } function claimERC721Airdrop( address token, address to, uint256[] calldata ids ) external override nonReentrant onlyOwner { require(token != _underlyingAsset, "BNFT: token can not be underlying asset"); require(token != address(this), "BNFT: token can not be self address"); for (uint256 i = 0; i < ids.length; i++) { IERC721Upgradeable(token).safeTransferFrom(address(this), to, ids[i]); } emit ClaimERC721Airdrop(token, to, ids); } function claimERC1155Airdrop( address token, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external override nonReentrant onlyOwner { require(token != _underlyingAsset, "BNFT: token can not be underlying asset"); require(token != address(this), "BNFT: token can not be self address"); IERC1155Upgradeable(token).safeBatchTransferFrom(address(this), to, ids, amounts, data); emit ClaimERC1155Airdrop(token, to, ids, amounts, data); } function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external pure override returns (bytes4) { operator; from; tokenId; data; return IERC721ReceiverUpgradeable.onERC721Received.selector; } function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external pure override returns (bytes4) { operator; from; id; value; data; return IERC1155ReceiverUpgradeable.onERC1155Received.selector; } function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external pure override returns (bytes4) { operator; from; ids; values; data; return IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector; } /** * @dev See {IBNFT-minterOf}. */ function minterOf(uint256 tokenId) external view override returns (address) { address minter = _minters[tokenId]; require(minter != address(0), "BNFT: minter query for nonexistent token"); return minter; } /** * @dev See {IBNFT-underlyingAsset}. */ function underlyingAsset() external view override returns (address) { return _underlyingAsset; } /** * @dev Being non transferrable, the bNFT token does not implement any of the * standard ERC721 functions for transfer and allowance. **/ function approve(address to, uint256 tokenId) public virtual override { to; tokenId; revert("APPROVAL_NOT_SUPPORTED"); } function setApprovalForAll(address operator, bool approved) public virtual override { operator; approved; revert("APPROVAL_NOT_SUPPORTED"); } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { from; to; tokenId; revert("TRANSFER_NOT_SUPPORTED"); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { from; to; tokenId; revert("TRANSFER_NOT_SUPPORTED"); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { from; to; tokenId; _data; revert("TRANSFER_NOT_SUPPORTED"); } function _transfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable) { from; to; tokenId; revert("TRANSFER_NOT_SUPPORTED"); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; interface IBNFT { /** * @dev Emitted when an bNFT is initialized * @param underlyingAsset_ The address of the underlying asset **/ event Initialized(address indexed underlyingAsset_); /** * @dev Emitted when the ownership is transferred * @param oldOwner The address of the old owner * @param newOwner The address of the new owner **/ event OwnershipTransferred(address oldOwner, address newOwner); /** * @dev Emitted on mint * @param user The address initiating the burn * @param nftAsset address of the underlying asset of NFT * @param nftTokenId token id of the underlying asset of NFT * @param owner The owner address receive the bNFT token **/ event Mint(address indexed user, address indexed nftAsset, uint256 nftTokenId, address indexed owner); /** * @dev Emitted on burn * @param user The address initiating the burn * @param nftAsset address of the underlying asset of NFT * @param nftTokenId token id of the underlying asset of NFT * @param owner The owner address of the burned bNFT token **/ event Burn(address indexed user, address indexed nftAsset, uint256 nftTokenId, address indexed owner); /** * @dev Emitted on flashLoan * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param nftAsset address of the underlying asset of NFT * @param tokenId The token id of the asset being flash borrowed **/ event FlashLoan(address indexed target, address indexed initiator, address indexed nftAsset, uint256 tokenId); event ClaimERC20Airdrop(address indexed token, address indexed to, uint256 amount); event ClaimERC721Airdrop(address indexed token, address indexed to, uint256[] ids); event ClaimERC1155Airdrop(address indexed token, address indexed to, uint256[] ids, uint256[] amounts, bytes data); /** * @dev Initializes the bNFT * @param underlyingAsset_ The address of the underlying asset of this bNFT (E.g. PUNK for bPUNK) */ function initialize( address underlyingAsset_, string calldata bNftName, string calldata bNftSymbol, address airdropAdmin_ ) external; /** * @dev Mints bNFT token to the user address * * Requirements: * - The caller can be contract address and EOA. * - `nftTokenId` must not exist. * * @param to The owner address receive the bNFT token * @param tokenId token id of the underlying asset of NFT **/ function mint(address to, uint256 tokenId) external; /** * @dev Burns user bNFT token * * Requirements: * - The caller can be contract address and EOA. * - `tokenId` must exist. * * @param tokenId token id of the underlying asset of NFT **/ function burn(uint256 tokenId) external; /** * @dev Allows smartcontracts to access the tokens within one transaction, as long as the tokens taken is returned. * * Requirements: * - `nftTokenIds` must exist. * * @param receiverAddress The address of the contract receiving the tokens, implementing the IFlashLoanReceiver interface * @param nftTokenIds token ids of the underlying asset * @param params Variadic packed params to pass to the receiver as extra information */ function flashLoan( address receiverAddress, uint256[] calldata nftTokenIds, bytes calldata params ) external; function claimERC20Airdrop( address token, address to, uint256 amount ) external; function claimERC721Airdrop( address token, address to, uint256[] calldata ids ) external; function claimERC1155Airdrop( address token, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; /** * @dev Returns the owner of the `nftTokenId` token. * * Requirements: * - `tokenId` must exist. * * @param tokenId token id of the underlying asset of NFT */ function minterOf(uint256 tokenId) external view returns (address); /** * @dev Returns the address of the underlying asset. */ function underlyingAsset() external view returns (address); /** * @dev Returns the contract-level metadata. */ function contractURI() external view returns (string memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; /** * @title IFlashLoanReceiver interface * @notice Interface for the IFlashLoanReceiver. * @author BEND * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address asset, uint256[] calldata tokenIds, address initiator, address operator, bytes calldata params ) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev 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 (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. 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 = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _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 = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); 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); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev 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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.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 {} /** * @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. * - `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 tokenId ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.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 ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal onlyInitializing { } function __ERC721Enumerable_init_unchained() internal onlyInitializing { } // 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[46] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, 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/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); }
Burns user bNFT token Requirements: - The caller can be contract address and EOA tokenId token id of the underlying asset of NFT/
function burn(uint256 tokenId) external override nonReentrant { require(_exists(tokenId), "BNFT: nonexist token"); require(_minters[tokenId] == _msgSender(), "BNFT: caller is not minter"); address tokenOwner = ERC721Upgradeable.ownerOf(tokenId); IERC721Upgradeable(_underlyingAsset).safeTransferFrom(address(this), _msgSender(), tokenId); _burn(tokenId); delete _minters[tokenId]; emit Burn(_msgSender(), _underlyingAsset, tokenId, tokenOwner); }
11,667,115
/** *Submitted for verification at Etherscan.io on 2021-09-10 */ /* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: ExchangerWithVirtualSynth.sol * * Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/ExchangerWithVirtualSynth.sol * Docs: https://docs.synthetix.io/contracts/ExchangerWithVirtualSynth * * Contract Dependencies: * - Exchanger * - IAddressResolver * - IExchanger * - MinimalProxyFactory * - MixinResolver * - MixinSystemSettings * - Owned * Libraries: * - SafeDecimalMath * - SafeMath * * MIT License * =========== * * Copyright (c) 2021 Synthetix * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity ^0.5.16; // https://docs.synthetix.io/contracts/source/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 { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } // https://docs.synthetix.io/contracts/source/interfaces/isynth interface ISynth { // Views function currencyKey() external view returns (bytes32); function transferableSynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to Synthetix function burn(address account, uint amount) external; function issue(address account, uint amount) external; } // https://docs.synthetix.io/contracts/source/interfaces/iissuer interface IIssuer { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function canBurnSynths(address account) external view returns (bool); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function collateralisationRatioAndAnyRatesInvalid(address _issuer) external view returns (uint cratio, bool anyRateIsInvalid); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance); function issuanceRatio() external view returns (uint); function lastIssueEvent(address account) external view returns (uint); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function minimumStakeTime() external view returns (uint); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey, bool excludeOtherCollateral) external view returns (uint); function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance) external view returns (uint transferable, bool anyRateIsInvalid); // Restricted: used internally to Synthetix function issueSynths(address from, uint amount) external; function issueSynthsOnBehalf( address issueFor, address from, uint amount ) external; function issueMaxSynths(address from) external; function issueMaxSynthsOnBehalf(address issueFor, address from) external; function burnSynths(address from, uint amount) external; function burnSynthsOnBehalf( address burnForAddress, address from, uint amount ) external; function burnSynthsToTarget(address from) external; function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external; function burnForRedemption( address deprecatedSynthProxy, address account, uint balance ) external; function liquidateDelinquentAccount( address account, uint susdAmount, address liquidator ) external returns (uint totalRedeemed, uint amountToLiquidate); } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/addressresolver contract AddressResolver is Owned, IAddressResolver { mapping(bytes32 => address) public repository; constructor(address _owner) public Owned(_owner) {} /* ========== RESTRICTED FUNCTIONS ========== */ function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner { require(names.length == destinations.length, "Input lengths must match"); for (uint i = 0; i < names.length; i++) { bytes32 name = names[i]; address destination = destinations[i]; repository[name] = destination; emit AddressImported(name, destination); } } /* ========= PUBLIC FUNCTIONS ========== */ function rebuildCaches(MixinResolver[] calldata destinations) external { for (uint i = 0; i < destinations.length; i++) { destinations[i].rebuildCache(); } } /* ========== VIEWS ========== */ function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) { for (uint i = 0; i < names.length; i++) { if (repository[names[i]] != destinations[i]) { return false; } } return true; } function getAddress(bytes32 name) external view returns (address) { return repository[name]; } function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) { address _foundAddress = repository[name]; require(_foundAddress != address(0), reason); return _foundAddress; } function getSynth(bytes32 key) external view returns (address) { IIssuer issuer = IIssuer(repository["Issuer"]); require(address(issuer) != address(0), "Cannot find Issuer address"); return address(issuer.synths(key)); } /* ========== EVENTS ========== */ event AddressImported(bytes32 name, address destination); } // Internal references // https://docs.synthetix.io/contracts/source/contracts/mixinresolver contract MixinResolver { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; constructor(address _resolver) internal { resolver = AddressResolver(_resolver); } /* ========== INTERNAL FUNCTIONS ========== */ function combineArrays(bytes32[] memory first, bytes32[] memory second) internal pure returns (bytes32[] memory combination) { combination = new bytes32[](first.length + second.length); for (uint i = 0; i < first.length; i++) { combination[i] = first[i]; } for (uint j = 0; j < second.length; j++) { combination[first.length + j] = second[j]; } } /* ========== PUBLIC FUNCTIONS ========== */ // Note: this function is public not external in order for it to be overridden and invoked via super in subclasses function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name))); addressCache[name] = destination; emit CacheUpdated(name, destination); } } /* ========== VIEWS ========== */ function isResolverCached() external view returns (bool) { bytes32[] memory requiredAddresses = resolverAddressesRequired(); for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } /* ========== INTERNAL FUNCTIONS ========== */ function requireAndGetAddress(bytes32 name) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name))); return _foundAddress; } /* ========== EVENTS ========== */ event CacheUpdated(bytes32 name, address destination); } // https://docs.synthetix.io/contracts/source/interfaces/iflexiblestorage interface IFlexibleStorage { // Views function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint); function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory); function getIntValue(bytes32 contractName, bytes32 record) external view returns (int); function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory); function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address); function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory); function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool); function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory); function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32); function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory); // Mutative functions function deleteUIntValue(bytes32 contractName, bytes32 record) external; function deleteIntValue(bytes32 contractName, bytes32 record) external; function deleteAddressValue(bytes32 contractName, bytes32 record) external; function deleteBoolValue(bytes32 contractName, bytes32 record) external; function deleteBytes32Value(bytes32 contractName, bytes32 record) external; function setUIntValue( bytes32 contractName, bytes32 record, uint value ) external; function setUIntValues( bytes32 contractName, bytes32[] calldata records, uint[] calldata values ) external; function setIntValue( bytes32 contractName, bytes32 record, int value ) external; function setIntValues( bytes32 contractName, bytes32[] calldata records, int[] calldata values ) external; function setAddressValue( bytes32 contractName, bytes32 record, address value ) external; function setAddressValues( bytes32 contractName, bytes32[] calldata records, address[] calldata values ) external; function setBoolValue( bytes32 contractName, bytes32 record, bool value ) external; function setBoolValues( bytes32 contractName, bytes32[] calldata records, bool[] calldata values ) external; function setBytes32Value( bytes32 contractName, bytes32 record, bytes32 value ) external; function setBytes32Values( bytes32 contractName, bytes32[] calldata records, bytes32[] calldata values ) external; } // Internal references // https://docs.synthetix.io/contracts/source/contracts/mixinsystemsettings contract MixinSystemSettings is MixinResolver { bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings"; bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs"; bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor"; bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio"; bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration"; bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold"; bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay"; bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio"; bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty"; bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod"; bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate"; bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime"; bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags"; bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled"; bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime"; bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit"; bytes32 internal constant SETTING_ETHER_WRAPPER_MAX_ETH = "etherWrapperMaxETH"; bytes32 internal constant SETTING_ETHER_WRAPPER_MINT_FEE_RATE = "etherWrapperMintFeeRate"; bytes32 internal constant SETTING_ETHER_WRAPPER_BURN_FEE_RATE = "etherWrapperBurnFeeRate"; bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage"; enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal} constructor(address _resolver) internal MixinResolver(_resolver) {} function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](1); addresses[0] = CONTRACT_FLEXIBLESTORAGE; } function flexibleStorage() internal view returns (IFlexibleStorage) { return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE)); } function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) { if (gasLimitType == CrossDomainMessageGasLimits.Deposit) { return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) { return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Reward) { return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) { return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT; } else { revert("Unknown gas limit type"); } } function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType)); } function getTradingRewardsEnabled() internal view returns (bool) { return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED); } function getWaitingPeriodSecs() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS); } function getPriceDeviationThresholdFactor() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR); } function getIssuanceRatio() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO); } function getFeePeriodDuration() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION); } function getTargetThreshold() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD); } function getLiquidationDelay() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY); } function getLiquidationRatio() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO); } function getLiquidationPenalty() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY); } function getRateStalePeriod() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD); } function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey)) ); } function getMinimumStakeTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME); } function getAggregatorWarningFlags() internal view returns (address) { return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS); } function getDebtSnapshotStaleTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME); } function getEtherWrapperMaxETH() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MAX_ETH); } function getEtherWrapperMintFeeRate() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MINT_FEE_RATE); } function getEtherWrapperBurnFeeRate() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_BURN_FEE_RATE); } } interface IVirtualSynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function synth() external view returns (ISynth); // Mutative functions function settle(address account) external; } // https://docs.synthetix.io/contracts/source/interfaces/iexchanger interface IExchanger { // Views function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) external view returns (uint amountAfterSettlement); function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool); function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint); function settlementOwing(address account, bytes32 currencyKey) external view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries ); function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool); function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint exchangeFeeRate); function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ); function priceDeviationThresholdFactor() external view returns (uint); function waitingPeriodSecs() external view returns (uint); // Mutative functions function exchange( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool virtualSynth, address rewardAddress, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external; function resetLastExchangeRate(bytes32[] calldata currencyKeys) external; function suspendSynthWithInvalidRate(bytes32 currencyKey) external; } /** * @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; } } // Libraries // https://docs.synthetix.io/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } // Computes `a - b`, setting the value to 0 if b > a. function floorsub(uint a, uint b) internal pure returns (uint) { return b >= a ? 0 : a - b; } } // https://docs.synthetix.io/contracts/source/interfaces/isystemstatus interface ISystemStatus { struct Status { bool canSuspend; bool canResume; } struct Suspension { bool suspended; // reason is an integer code, // 0 => no reason, 1 => upgrading, 2+ => defined by system usage uint248 reason; } // Views function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume); function requireSystemActive() external view; function requireIssuanceActive() external view; function requireExchangeActive() external view; function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function requireSynthActive(bytes32 currencyKey) external view; function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function systemSuspension() external view returns (bool suspended, uint248 reason); function issuanceSuspension() external view returns (bool suspended, uint248 reason); function exchangeSuspension() external view returns (bool suspended, uint248 reason); function synthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function getSynthExchangeSuspensions(bytes32[] calldata synths) external view returns (bool[] memory exchangeSuspensions, uint256[] memory reasons); function getSynthSuspensions(bytes32[] calldata synths) external view returns (bool[] memory suspensions, uint256[] memory reasons); // Restricted functions function suspendSynth(bytes32 currencyKey, uint256 reason) external; function updateAccessControl( bytes32 section, address account, bool canSuspend, bool canResume ) external; } // https://docs.synthetix.io/contracts/source/interfaces/ierc20 interface IERC20 { // ERC20 Optional Views function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); // Views function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); // Mutative functions function transfer(address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); // Events event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } // https://docs.synthetix.io/contracts/source/interfaces/iexchangestate interface IExchangeState { // Views struct ExchangeEntry { bytes32 src; uint amount; bytes32 dest; uint amountReceived; uint exchangeFeeRate; uint timestamp; uint roundIdForSrc; uint roundIdForDest; } function getLengthOfEntries(address account, bytes32 currencyKey) external view returns (uint); function getEntryAt( address account, bytes32 currencyKey, uint index ) external view returns ( bytes32 src, uint amount, bytes32 dest, uint amountReceived, uint exchangeFeeRate, uint timestamp, uint roundIdForSrc, uint roundIdForDest ); function getMaxTimestamp(address account, bytes32 currencyKey) external view returns (uint); // Mutative functions function appendExchangeEntry( address account, bytes32 src, uint amount, bytes32 dest, uint amountReceived, uint exchangeFeeRate, uint timestamp, uint roundIdForSrc, uint roundIdForDest ) external; function removeEntries(address account, bytes32 currencyKey) external; } // https://docs.synthetix.io/contracts/source/interfaces/iexchangerates interface IExchangeRates { // Structs struct RateAndUpdatedTime { uint216 rate; uint40 time; } struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozenAtUpperLimit; bool frozenAtLowerLimit; } // Views function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function canFreezeRate(bytes32 currencyKey) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozenAtUpperLimit, bool frozenAtLowerLimit ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); // Mutative functions function freezeRate(bytes32 currencyKey) external; } // https://docs.synthetix.io/contracts/source/interfaces/isynthetix interface ISynthetix { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint); function isWaitingPeriod(bytes32 currencyKey) external view returns (bool); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey) external view returns (uint); function totalIssuedSynthsExcludeOtherCollateral(bytes32 currencyKey) external view returns (uint); function transferableSynthetix(address account) external view returns (uint transferable); // Mutative Functions function burnSynths(uint amount) external; function burnSynthsOnBehalf(address burnForAddress, uint amount) external; function burnSynthsToTarget() external; function burnSynthsToTargetOnBehalf(address burnForAddress) external; function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address rewardAddress, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithTrackingForInitiator( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address rewardAddress, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address rewardAddress, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function issueMaxSynths() external; function issueMaxSynthsOnBehalf(address issueForAddress) external; function issueSynths(uint amount) external; function issueSynthsOnBehalf(address issueForAddress, uint amount) external; function mint() external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; } // https://docs.synthetix.io/contracts/source/interfaces/ifeepool interface IFeePool { // Views // solhint-disable-next-line func-name-mixedcase function FEE_ADDRESS() external view returns (address); function feesAvailable(address account) external view returns (uint, uint); function feePeriodDuration() external view returns (uint); function isFeesClaimable(address account) external view returns (bool); function targetThreshold() external view returns (uint); function totalFeesAvailable() external view returns (uint); function totalRewardsAvailable() external view returns (uint); // Mutative Functions function claimFees() external returns (bool); function claimOnBehalf(address claimingForAddress) external returns (bool); function closeCurrentFeePeriod() external; // Restricted: used internally to Synthetix function appendAccountIssuanceRecord( address account, uint lockedAmount, uint debtEntryIndex ) external; function recordFeePaid(uint sUSDAmount) external; function setRewardsToDistribute(uint amount) external; } // https://docs.synthetix.io/contracts/source/interfaces/idelegateapprovals interface IDelegateApprovals { // Views function canBurnFor(address authoriser, address delegate) external view returns (bool); function canIssueFor(address authoriser, address delegate) external view returns (bool); function canClaimFor(address authoriser, address delegate) external view returns (bool); function canExchangeFor(address authoriser, address delegate) external view returns (bool); // Mutative function approveAllDelegatePowers(address delegate) external; function removeAllDelegatePowers(address delegate) external; function approveBurnOnBehalf(address delegate) external; function removeBurnOnBehalf(address delegate) external; function approveIssueOnBehalf(address delegate) external; function removeIssueOnBehalf(address delegate) external; function approveClaimOnBehalf(address delegate) external; function removeClaimOnBehalf(address delegate) external; function approveExchangeOnBehalf(address delegate) external; function removeExchangeOnBehalf(address delegate) external; } // https://docs.synthetix.io/contracts/source/interfaces/itradingrewards interface ITradingRewards { /* ========== VIEWS ========== */ function getAvailableRewards() external view returns (uint); function getUnassignedRewards() external view returns (uint); function getRewardsToken() external view returns (address); function getPeriodController() external view returns (address); function getCurrentPeriod() external view returns (uint); function getPeriodIsClaimable(uint periodID) external view returns (bool); function getPeriodIsFinalized(uint periodID) external view returns (bool); function getPeriodRecordedFees(uint periodID) external view returns (uint); function getPeriodTotalRewards(uint periodID) external view returns (uint); function getPeriodAvailableRewards(uint periodID) external view returns (uint); function getUnaccountedFeesForAccountForPeriod(address account, uint periodID) external view returns (uint); function getAvailableRewardsForAccountForPeriod(address account, uint periodID) external view returns (uint); function getAvailableRewardsForAccountForPeriods(address account, uint[] calldata periodIDs) external view returns (uint totalRewards); /* ========== MUTATIVE FUNCTIONS ========== */ function claimRewardsForPeriod(uint periodID) external; function claimRewardsForPeriods(uint[] calldata periodIDs) external; /* ========== RESTRICTED FUNCTIONS ========== */ function recordExchangeFeeForAccount(uint usdFeeAmount, address account) external; function closeCurrentPeriodWithRewards(uint rewards) external; function recoverTokens(address tokenAddress, address recoverAddress) external; function recoverUnassignedRewardTokens(address recoverAddress) external; function recoverAssignedRewardTokensAndDestroyPeriod(address recoverAddress, uint periodID) external; function setPeriodController(address newPeriodController) external; } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/proxy contract Proxy is Owned { Proxyable public target; constructor(address _owner) public Owned(_owner) {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function _emit( bytes calldata callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4 ) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { /* The first 32 bytes of callData contain its length (as specified by the abi). * Length is assumed to be a uint256 and therefore maximum of 32 bytes * in length. It is also leftpadded to be a multiple of 32 bytes. * This means moving call_data across 32 bytes guarantees we correctly access * the data itself. */ switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } // solhint-disable no-complex-fallback function() external payable { // Mutable call setting Proxyable.messageSender as this is using call not delegatecall target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly forward ether to the underlying contract as well. */ let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "Must be proxy target"); _; } event TargetUpdated(Proxyable newTarget); } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/proxyable contract Proxyable is Owned { // This contract should be treated like an abstract contract /* The proxy this contract exists behind. */ Proxy public proxy; Proxy public integrationProxy; /* The caller of the proxy, passed through to this contract. * Note that every function using this member must apply the onlyProxy or * optionalProxy modifiers, otherwise their invocations can use stale values. */ address public messageSender; constructor(address payable _proxy) internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address payable _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setIntegrationProxy(address payable _integrationProxy) external onlyOwner { integrationProxy = Proxy(_integrationProxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { _onlyProxy(); _; } function _onlyProxy() private view { require(Proxy(msg.sender) == proxy || Proxy(msg.sender) == integrationProxy, "Only the proxy can call"); } modifier optionalProxy { _optionalProxy(); _; } function _optionalProxy() private { if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) { messageSender = msg.sender; } } modifier optionalProxy_onlyOwner { _optionalProxy_onlyOwner(); _; } // solhint-disable-next-line func-name-mixedcase function _optionalProxy_onlyOwner() private { if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) { messageSender = msg.sender; } require(messageSender == owner, "Owner only function"); } event ProxyUpdated(address proxyAddress); } // Inheritance // Libraries // Internal references // Used to have strongly-typed access to internal mutative functions in Synthetix interface ISynthetixInternal { function emitExchangeTracking( bytes32 trackingCode, bytes32 toCurrencyKey, uint256 toAmount, uint256 fee ) external; function emitSynthExchange( address account, bytes32 fromCurrencyKey, uint fromAmount, bytes32 toCurrencyKey, uint toAmount, address toAddress ) external; function emitExchangeReclaim( address account, bytes32 currencyKey, uint amount ) external; function emitExchangeRebate( address account, bytes32 currencyKey, uint amount ) external; } interface IExchangerInternalDebtCache { function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external; function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external; } // https://docs.synthetix.io/contracts/source/contracts/exchanger contract Exchanger is Owned, MixinSystemSettings, IExchanger { using SafeMath for uint; using SafeDecimalMath for uint; struct ExchangeEntrySettlement { bytes32 src; uint amount; bytes32 dest; uint reclaim; uint rebate; uint srcRoundIdAtPeriodEnd; uint destRoundIdAtPeriodEnd; uint timestamp; } bytes32 public constant CONTRACT_NAME = "Exchanger"; bytes32 private constant sUSD = "sUSD"; // SIP-65: Decentralized circuit breaker uint public constant CIRCUIT_BREAKER_SUSPENSION_REASON = 65; mapping(bytes32 => uint) public lastExchangeRate; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_EXCHANGESTATE = "ExchangeState"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 private constant CONTRACT_SYNTHETIX = "Synthetix"; bytes32 private constant CONTRACT_FEEPOOL = "FeePool"; bytes32 private constant CONTRACT_TRADING_REWARDS = "TradingRewards"; bytes32 private constant CONTRACT_DELEGATEAPPROVALS = "DelegateApprovals"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_DEBTCACHE = "DebtCache"; constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {} /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](9); newAddresses[0] = CONTRACT_SYSTEMSTATUS; newAddresses[1] = CONTRACT_EXCHANGESTATE; newAddresses[2] = CONTRACT_EXRATES; newAddresses[3] = CONTRACT_SYNTHETIX; newAddresses[4] = CONTRACT_FEEPOOL; newAddresses[5] = CONTRACT_TRADING_REWARDS; newAddresses[6] = CONTRACT_DELEGATEAPPROVALS; newAddresses[7] = CONTRACT_ISSUER; newAddresses[8] = CONTRACT_DEBTCACHE; addresses = combineArrays(existingAddresses, newAddresses); } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function exchangeState() internal view returns (IExchangeState) { return IExchangeState(requireAndGetAddress(CONTRACT_EXCHANGESTATE)); } function exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES)); } function synthetix() internal view returns (ISynthetix) { return ISynthetix(requireAndGetAddress(CONTRACT_SYNTHETIX)); } function feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL)); } function tradingRewards() internal view returns (ITradingRewards) { return ITradingRewards(requireAndGetAddress(CONTRACT_TRADING_REWARDS)); } function delegateApprovals() internal view returns (IDelegateApprovals) { return IDelegateApprovals(requireAndGetAddress(CONTRACT_DELEGATEAPPROVALS)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function debtCache() internal view returns (IExchangerInternalDebtCache) { return IExchangerInternalDebtCache(requireAndGetAddress(CONTRACT_DEBTCACHE)); } function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) public view returns (uint) { return secsLeftInWaitingPeriodForExchange(exchangeState().getMaxTimestamp(account, currencyKey)); } function waitingPeriodSecs() external view returns (uint) { return getWaitingPeriodSecs(); } function tradingRewardsEnabled() external view returns (bool) { return getTradingRewardsEnabled(); } function priceDeviationThresholdFactor() external view returns (uint) { return getPriceDeviationThresholdFactor(); } function settlementOwing(address account, bytes32 currencyKey) public view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries ) { (reclaimAmount, rebateAmount, numEntries, ) = _settlementOwing(account, currencyKey); } // Internal function to emit events for each individual rebate and reclaim entry function _settlementOwing(address account, bytes32 currencyKey) internal view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries, ExchangeEntrySettlement[] memory ) { // Need to sum up all reclaim and rebate amounts for the user and the currency key numEntries = exchangeState().getLengthOfEntries(account, currencyKey); // For each unsettled exchange ExchangeEntrySettlement[] memory settlements = new ExchangeEntrySettlement[](numEntries); for (uint i = 0; i < numEntries; i++) { uint reclaim; uint rebate; // fetch the entry from storage IExchangeState.ExchangeEntry memory exchangeEntry = _getExchangeEntry(account, currencyKey, i); // determine the last round ids for src and dest pairs when period ended or latest if not over (uint srcRoundIdAtPeriodEnd, uint destRoundIdAtPeriodEnd) = getRoundIdsAtPeriodEnd(exchangeEntry); // given these round ids, determine what effective value they should have received uint destinationAmount = exchangeRates().effectiveValueAtRound( exchangeEntry.src, exchangeEntry.amount, exchangeEntry.dest, srcRoundIdAtPeriodEnd, destRoundIdAtPeriodEnd ); // and deduct the fee from this amount using the exchangeFeeRate from storage uint amountShouldHaveReceived = _getAmountReceivedForExchange(destinationAmount, exchangeEntry.exchangeFeeRate); // SIP-65 settlements where the amount at end of waiting period is beyond the threshold, then // settle with no reclaim or rebate if (!_isDeviationAboveThreshold(exchangeEntry.amountReceived, amountShouldHaveReceived)) { if (exchangeEntry.amountReceived > amountShouldHaveReceived) { // if they received more than they should have, add to the reclaim tally reclaim = exchangeEntry.amountReceived.sub(amountShouldHaveReceived); reclaimAmount = reclaimAmount.add(reclaim); } else if (amountShouldHaveReceived > exchangeEntry.amountReceived) { // if less, add to the rebate tally rebate = amountShouldHaveReceived.sub(exchangeEntry.amountReceived); rebateAmount = rebateAmount.add(rebate); } } settlements[i] = ExchangeEntrySettlement({ src: exchangeEntry.src, amount: exchangeEntry.amount, dest: exchangeEntry.dest, reclaim: reclaim, rebate: rebate, srcRoundIdAtPeriodEnd: srcRoundIdAtPeriodEnd, destRoundIdAtPeriodEnd: destRoundIdAtPeriodEnd, timestamp: exchangeEntry.timestamp }); } return (reclaimAmount, rebateAmount, numEntries, settlements); } function _getExchangeEntry( address account, bytes32 currencyKey, uint index ) internal view returns (IExchangeState.ExchangeEntry memory) { ( bytes32 src, uint amount, bytes32 dest, uint amountReceived, uint exchangeFeeRate, uint timestamp, uint roundIdForSrc, uint roundIdForDest ) = exchangeState().getEntryAt(account, currencyKey, index); return IExchangeState.ExchangeEntry({ src: src, amount: amount, dest: dest, amountReceived: amountReceived, exchangeFeeRate: exchangeFeeRate, timestamp: timestamp, roundIdForSrc: roundIdForSrc, roundIdForDest: roundIdForDest }); } function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool) { if (maxSecsLeftInWaitingPeriod(account, currencyKey) != 0) { return true; } (uint reclaimAmount, , , ) = _settlementOwing(account, currencyKey); return reclaimAmount > 0; } /* ========== SETTERS ========== */ function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) public view returns (uint amountAfterSettlement) { amountAfterSettlement = amount; // balance of a synth will show an amount after settlement uint balanceOfSourceAfterSettlement = IERC20(address(issuer().synths(currencyKey))).balanceOf(from); // when there isn't enough supply (either due to reclamation settlement or because the number is too high) if (amountAfterSettlement > balanceOfSourceAfterSettlement) { // then the amount to exchange is reduced to their remaining supply amountAfterSettlement = balanceOfSourceAfterSettlement; } if (refunded > 0) { amountAfterSettlement = amountAfterSettlement.add(refunded); } } function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool) { return _isSynthRateInvalid(currencyKey, exchangeRates().rateForCurrency(currencyKey)); } /* ========== MUTATIVE FUNCTIONS ========== */ function exchange( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool virtualSynth, address rewardAddress, bytes32 trackingCode ) external onlySynthetixorSynth returns (uint amountReceived, IVirtualSynth vSynth) { uint fee; if (from != exchangeForAddress) { require(delegateApprovals().canExchangeFor(exchangeForAddress, from), "Not approved to act on behalf"); } (amountReceived, fee, vSynth) = _exchange( exchangeForAddress, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, virtualSynth ); if (fee > 0 && rewardAddress != address(0) && getTradingRewardsEnabled()) { tradingRewards().recordExchangeFeeForAccount(fee, rewardAddress); } if (trackingCode != bytes32(0)) { ISynthetixInternal(address(synthetix())).emitExchangeTracking( trackingCode, destinationCurrencyKey, amountReceived, fee ); } } function _suspendIfRateInvalid(bytes32 currencyKey, uint rate) internal returns (bool circuitBroken) { if (_isSynthRateInvalid(currencyKey, rate)) { systemStatus().suspendSynth(currencyKey, CIRCUIT_BREAKER_SUSPENSION_REASON); circuitBroken = true; } else { lastExchangeRate[currencyKey] = rate; } } function _updateSNXIssuedDebtOnExchange(bytes32[2] memory currencyKeys, uint[2] memory currencyRates) internal { bool includesSUSD = currencyKeys[0] == sUSD || currencyKeys[1] == sUSD; uint numKeys = includesSUSD ? 2 : 3; bytes32[] memory keys = new bytes32[](numKeys); keys[0] = currencyKeys[0]; keys[1] = currencyKeys[1]; uint[] memory rates = new uint[](numKeys); rates[0] = currencyRates[0]; rates[1] = currencyRates[1]; if (!includesSUSD) { keys[2] = sUSD; // And we'll also update sUSD to account for any fees if it wasn't one of the exchanged currencies rates[2] = SafeDecimalMath.unit(); } // Note that exchanges can't invalidate the debt cache, since if a rate is invalid, // the exchange will have failed already. debtCache().updateCachedSynthDebtsWithRates(keys, rates); } function _settleAndCalcSourceAmountRemaining( uint sourceAmount, address from, bytes32 sourceCurrencyKey ) internal returns (uint sourceAmountAfterSettlement) { (, uint refunded, uint numEntriesSettled) = _internalSettle(from, sourceCurrencyKey, false); sourceAmountAfterSettlement = sourceAmount; // when settlement was required if (numEntriesSettled > 0) { // ensure the sourceAmount takes this into account sourceAmountAfterSettlement = calculateAmountAfterSettlement(from, sourceCurrencyKey, sourceAmount, refunded); } } function _exchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool virtualSynth ) internal returns ( uint amountReceived, uint fee, IVirtualSynth vSynth ) { _ensureCanExchange(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); uint sourceAmountAfterSettlement = _settleAndCalcSourceAmountRemaining(sourceAmount, from, sourceCurrencyKey); // If, after settlement the user has no balance left (highly unlikely), then return to prevent // emitting events of 0 and don't revert so as to ensure the settlement queue is emptied if (sourceAmountAfterSettlement == 0) { return (0, 0, IVirtualSynth(0)); } uint exchangeFeeRate; uint sourceRate; uint destinationRate; // Note: `fee` is denominated in the destinationCurrencyKey. (amountReceived, fee, exchangeFeeRate, sourceRate, destinationRate) = _getAmountsForExchangeMinusFees( sourceAmountAfterSettlement, sourceCurrencyKey, destinationCurrencyKey ); // SIP-65: Decentralized Circuit Breaker if ( _suspendIfRateInvalid(sourceCurrencyKey, sourceRate) || _suspendIfRateInvalid(destinationCurrencyKey, destinationRate) ) { return (0, 0, IVirtualSynth(0)); } // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. vSynth = _convert( sourceCurrencyKey, from, sourceAmountAfterSettlement, destinationCurrencyKey, amountReceived, destinationAddress, virtualSynth ); // When using a virtual synth, it becomes the destinationAddress for event and settlement tracking if (vSynth != IVirtualSynth(0)) { destinationAddress = address(vSynth); } // Remit the fee if required if (fee > 0) { // Normalize fee to sUSD // Note: `fee` is being reused to avoid stack too deep errors. fee = exchangeRates().effectiveValue(destinationCurrencyKey, fee, sUSD); // Remit the fee in sUSDs issuer().synths(sUSD).issue(feePool().FEE_ADDRESS(), fee); // Tell the fee pool about this feePool().recordFeePaid(fee); } // Note: As of this point, `fee` is denominated in sUSD. // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. // But we will update the debt snapshot in case exchange rates have fluctuated since the last exchange // in these currencies _updateSNXIssuedDebtOnExchange([sourceCurrencyKey, destinationCurrencyKey], [sourceRate, destinationRate]); // Let the DApps know there was a Synth exchange ISynthetixInternal(address(synthetix())).emitSynthExchange( from, sourceCurrencyKey, sourceAmountAfterSettlement, destinationCurrencyKey, amountReceived, destinationAddress ); // iff the waiting period is gt 0 if (getWaitingPeriodSecs() > 0) { // persist the exchange information for the dest key appendExchange( destinationAddress, sourceCurrencyKey, sourceAmountAfterSettlement, destinationCurrencyKey, amountReceived, exchangeFeeRate ); } } function _convert( bytes32 sourceCurrencyKey, address from, uint sourceAmountAfterSettlement, bytes32 destinationCurrencyKey, uint amountReceived, address recipient, bool virtualSynth ) internal returns (IVirtualSynth vSynth) { // Burn the source amount issuer().synths(sourceCurrencyKey).burn(from, sourceAmountAfterSettlement); // Issue their new synths ISynth dest = issuer().synths(destinationCurrencyKey); if (virtualSynth) { Proxyable synth = Proxyable(address(dest)); vSynth = _createVirtualSynth(IERC20(address(synth.proxy())), recipient, amountReceived, destinationCurrencyKey); dest.issue(address(vSynth), amountReceived); } else { dest.issue(recipient, amountReceived); } } function _createVirtualSynth( IERC20, address, uint, bytes32 ) internal returns (IVirtualSynth) { revert("Cannot be run on this layer"); } // Note: this function can intentionally be called by anyone on behalf of anyone else (the caller just pays the gas) function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntriesSettled ) { systemStatus().requireSynthActive(currencyKey); return _internalSettle(from, currencyKey, true); } function suspendSynthWithInvalidRate(bytes32 currencyKey) external { systemStatus().requireSystemActive(); require(issuer().synths(currencyKey) != ISynth(0), "No such synth"); require(_isSynthRateInvalid(currencyKey, exchangeRates().rateForCurrency(currencyKey)), "Synth price is valid"); systemStatus().suspendSynth(currencyKey, CIRCUIT_BREAKER_SUSPENSION_REASON); } // SIP-78 function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external onlyExchangeRates { require(rate > 0, "Rate must be above 0"); lastExchangeRate[currencyKey] = rate; } // SIP-139 function resetLastExchangeRate(bytes32[] calldata currencyKeys) external onlyOwner { (uint[] memory rates, bool anyRateInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys); require(!anyRateInvalid, "Rates for given synths not valid"); for (uint i = 0; i < currencyKeys.length; i++) { lastExchangeRate[currencyKeys[i]] = rates[i]; } } /* ========== INTERNAL FUNCTIONS ========== */ function _ensureCanExchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) internal view { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); bytes32[] memory synthKeys = new bytes32[](2); synthKeys[0] = sourceCurrencyKey; synthKeys[1] = destinationCurrencyKey; require(!exchangeRates().anyRateIsInvalid(synthKeys), "Src/dest rate invalid or not found"); } function _isSynthRateInvalid(bytes32 currencyKey, uint currentRate) internal view returns (bool) { if (currentRate == 0) { return true; } uint lastRateFromExchange = lastExchangeRate[currencyKey]; if (lastRateFromExchange > 0) { return _isDeviationAboveThreshold(lastRateFromExchange, currentRate); } // if no last exchange for this synth, then we need to look up last 3 rates (+1 for current rate) (uint[] memory rates, ) = exchangeRates().ratesAndUpdatedTimeForCurrencyLastNRounds(currencyKey, 4); // start at index 1 to ignore current rate for (uint i = 1; i < rates.length; i++) { // ignore any empty rates in the past (otherwise we will never be able to get validity) if (rates[i] > 0 && _isDeviationAboveThreshold(rates[i], currentRate)) { return true; } } return false; } function _isDeviationAboveThreshold(uint base, uint comparison) internal view returns (bool) { if (base == 0 || comparison == 0) { return true; } uint factor; if (comparison > base) { factor = comparison.divideDecimal(base); } else { factor = base.divideDecimal(comparison); } return factor >= getPriceDeviationThresholdFactor(); } function _internalSettle( address from, bytes32 currencyKey, bool updateCache ) internal returns ( uint reclaimed, uint refunded, uint numEntriesSettled ) { require(maxSecsLeftInWaitingPeriod(from, currencyKey) == 0, "Cannot settle during waiting period"); (uint reclaimAmount, uint rebateAmount, uint entries, ExchangeEntrySettlement[] memory settlements) = _settlementOwing(from, currencyKey); if (reclaimAmount > rebateAmount) { reclaimed = reclaimAmount.sub(rebateAmount); reclaim(from, currencyKey, reclaimed); } else if (rebateAmount > reclaimAmount) { refunded = rebateAmount.sub(reclaimAmount); refund(from, currencyKey, refunded); } // by checking a reclaim or refund we also check that the currency key is still a valid synth, // as the deviation check will return 0 if the synth has been removed. if (updateCache && (reclaimed > 0 || refunded > 0)) { bytes32[] memory key = new bytes32[](1); key[0] = currencyKey; debtCache().updateCachedSynthDebts(key); } // emit settlement event for each settled exchange entry for (uint i = 0; i < settlements.length; i++) { emit ExchangeEntrySettled( from, settlements[i].src, settlements[i].amount, settlements[i].dest, settlements[i].reclaim, settlements[i].rebate, settlements[i].srcRoundIdAtPeriodEnd, settlements[i].destRoundIdAtPeriodEnd, settlements[i].timestamp ); } numEntriesSettled = entries; // Now remove all entries, even if no reclaim and no rebate exchangeState().removeEntries(from, currencyKey); } function reclaim( address from, bytes32 currencyKey, uint amount ) internal { // burn amount from user issuer().synths(currencyKey).burn(from, amount); ISynthetixInternal(address(synthetix())).emitExchangeReclaim(from, currencyKey, amount); } function refund( address from, bytes32 currencyKey, uint amount ) internal { // issue amount to user issuer().synths(currencyKey).issue(from, amount); ISynthetixInternal(address(synthetix())).emitExchangeRebate(from, currencyKey, amount); } function secsLeftInWaitingPeriodForExchange(uint timestamp) internal view returns (uint) { uint _waitingPeriodSecs = getWaitingPeriodSecs(); if (timestamp == 0 || now >= timestamp.add(_waitingPeriodSecs)) { return 0; } return timestamp.add(_waitingPeriodSecs).sub(now); } function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint exchangeFeeRate) { exchangeFeeRate = _feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); } function _feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) internal view returns (uint exchangeFeeRate) { // Get the exchange fee rate as per destination currencyKey exchangeFeeRate = getExchangeFeeRate(destinationCurrencyKey); if (sourceCurrencyKey == sUSD || destinationCurrencyKey == sUSD) { return exchangeFeeRate; } // Is this a swing trade? long to short or short to long skipping sUSD. if ( (sourceCurrencyKey[0] == 0x73 && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey[0] == 0x73) ) { // Double the exchange fee exchangeFeeRate = exchangeFeeRate.mul(2); } return exchangeFeeRate; } function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ) { (amountReceived, fee, exchangeFeeRate, , ) = _getAmountsForExchangeMinusFees( sourceAmount, sourceCurrencyKey, destinationCurrencyKey ); } function _getAmountsForExchangeMinusFees( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) internal view returns ( uint amountReceived, uint fee, uint exchangeFeeRate, uint sourceRate, uint destinationRate ) { uint destinationAmount; (destinationAmount, sourceRate, destinationRate) = exchangeRates().effectiveValueAndRates( sourceCurrencyKey, sourceAmount, destinationCurrencyKey ); exchangeFeeRate = _feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = _getAmountReceivedForExchange(destinationAmount, exchangeFeeRate); fee = destinationAmount.sub(amountReceived); } function _getAmountReceivedForExchange(uint destinationAmount, uint exchangeFeeRate) internal pure returns (uint amountReceived) { amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); } function appendExchange( address account, bytes32 src, uint amount, bytes32 dest, uint amountReceived, uint exchangeFeeRate ) internal { IExchangeRates exRates = exchangeRates(); uint roundIdForSrc = exRates.getCurrentRoundId(src); uint roundIdForDest = exRates.getCurrentRoundId(dest); exchangeState().appendExchangeEntry( account, src, amount, dest, amountReceived, exchangeFeeRate, now, roundIdForSrc, roundIdForDest ); emit ExchangeEntryAppended( account, src, amount, dest, amountReceived, exchangeFeeRate, roundIdForSrc, roundIdForDest ); } function getRoundIdsAtPeriodEnd(IExchangeState.ExchangeEntry memory exchangeEntry) internal view returns (uint srcRoundIdAtPeriodEnd, uint destRoundIdAtPeriodEnd) { IExchangeRates exRates = exchangeRates(); uint _waitingPeriodSecs = getWaitingPeriodSecs(); srcRoundIdAtPeriodEnd = exRates.getLastRoundIdBeforeElapsedSecs( exchangeEntry.src, exchangeEntry.roundIdForSrc, exchangeEntry.timestamp, _waitingPeriodSecs ); destRoundIdAtPeriodEnd = exRates.getLastRoundIdBeforeElapsedSecs( exchangeEntry.dest, exchangeEntry.roundIdForDest, exchangeEntry.timestamp, _waitingPeriodSecs ); } // ========== MODIFIERS ========== modifier onlySynthetixorSynth() { ISynthetix _synthetix = synthetix(); require( msg.sender == address(_synthetix) || _synthetix.synthsByAddress(msg.sender) != bytes32(0), "Exchanger: Only synthetix or a synth contract can perform this action" ); _; } modifier onlyExchangeRates() { IExchangeRates _exchangeRates = exchangeRates(); require(msg.sender == address(_exchangeRates), "Restricted to ExchangeRates"); _; } // ========== EVENTS ========== event ExchangeEntryAppended( address indexed account, bytes32 src, uint256 amount, bytes32 dest, uint256 amountReceived, uint256 exchangeFeeRate, uint256 roundIdForSrc, uint256 roundIdForDest ); event ExchangeEntrySettled( address indexed from, bytes32 src, uint256 amount, bytes32 dest, uint256 reclaim, uint256 rebate, uint256 srcRoundIdAtPeriodEnd, uint256 destRoundIdAtPeriodEnd, uint256 exchangeTimestamp ); } // https://docs.synthetix.io/contracts/source/contracts/minimalproxyfactory contract MinimalProxyFactory { function _cloneAsMinimalProxy(address _base, string memory _revertMsg) internal returns (address clone) { bytes memory createData = _generateMinimalProxyCreateData(_base); assembly { clone := create( 0, // no value add(createData, 0x20), // data 55 // data is always 55 bytes (10 constructor + 45 code) ) } // If CREATE fails for some reason, address(0) is returned require(clone != address(0), _revertMsg); } function _generateMinimalProxyCreateData(address _base) internal pure returns (bytes memory) { return abi.encodePacked( //---- constructor ----- bytes10(0x3d602d80600a3d3981f3), //---- proxy code ----- bytes10(0x363d3d373d3d3d363d73), _base, bytes15(0x5af43d82803e903d91602b57fd5bf3) ); } } // Inheritance // Internal references interface IVirtualSynthInternal { function initialize( IERC20 _synth, IAddressResolver _resolver, address _recipient, uint _amount, bytes32 _currencyKey ) external; } // https://docs.synthetix.io/contracts/source/contracts/exchangerwithvirtualsynth contract ExchangerWithVirtualSynth is MinimalProxyFactory, Exchanger { bytes32 public constant CONTRACT_NAME = "ExchangerWithVirtualSynth"; constructor(address _owner, address _resolver) public MinimalProxyFactory() Exchanger(_owner, _resolver) {} /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_VIRTUALSYNTH_MASTERCOPY = "VirtualSynthMastercopy"; function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = Exchanger.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](1); newAddresses[0] = CONTRACT_VIRTUALSYNTH_MASTERCOPY; addresses = combineArrays(existingAddresses, newAddresses); } /* ========== INTERNAL FUNCTIONS ========== */ function _virtualSynthMastercopy() internal view returns (address) { return requireAndGetAddress(CONTRACT_VIRTUALSYNTH_MASTERCOPY); } function _createVirtualSynth( IERC20 synth, address recipient, uint amount, bytes32 currencyKey ) internal returns (IVirtualSynth) { // prevent inverse synths from being allowed due to purgeability require(currencyKey[0] != 0x69, "Cannot virtualize this synth"); IVirtualSynthInternal vSynth = IVirtualSynthInternal(_cloneAsMinimalProxy(_virtualSynthMastercopy(), "Could not create new vSynth")); vSynth.initialize(synth, resolver, recipient, amount, currencyKey); emit VirtualSynthCreated(address(synth), recipient, address(vSynth), currencyKey, amount); return IVirtualSynth(address(vSynth)); } event VirtualSynthCreated( address indexed synth, address indexed recipient, address vSynth, bytes32 currencyKey, uint amount ); }
by checking a reclaim or refund we also check that the currency key is still a valid synth, as the deviation check will return 0 if the synth has been removed. emit settlement event for each settled exchange entry
function _internalSettle( address from, bytes32 currencyKey, bool updateCache ) internal returns ( uint reclaimed, uint refunded, uint numEntriesSettled ) { require(maxSecsLeftInWaitingPeriod(from, currencyKey) == 0, "Cannot settle during waiting period"); (uint reclaimAmount, uint rebateAmount, uint entries, ExchangeEntrySettlement[] memory settlements) = _settlementOwing(from, currencyKey); if (reclaimAmount > rebateAmount) { reclaimed = reclaimAmount.sub(rebateAmount); reclaim(from, currencyKey, reclaimed); refunded = rebateAmount.sub(reclaimAmount); refund(from, currencyKey, refunded); } if (updateCache && (reclaimed > 0 || refunded > 0)) { bytes32[] memory key = new bytes32[](1); key[0] = currencyKey; debtCache().updateCachedSynthDebts(key); } for (uint i = 0; i < settlements.length; i++) { emit ExchangeEntrySettled( from, settlements[i].src, settlements[i].amount, settlements[i].dest, settlements[i].reclaim, settlements[i].rebate, settlements[i].srcRoundIdAtPeriodEnd, settlements[i].destRoundIdAtPeriodEnd, settlements[i].timestamp ); } numEntriesSettled = entries; }
6,635,606
./full_match/80001/0x35C94EcA841160336c4b4bd648b55e52034448e1/sources/contracts/Contract.sol
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 override { require( account == _msgSender(), "AccessControl: can only renounce roles for self" ); _revokeRole(role, account); }
873,084
./full_match/97/0x3D6C3e1AD35183950ad082777d033E47d512033D/sources/project_/contracts/piNFT.sol
Lazy Mints an nft to a specified address. _to address to mint the piNFT to. _uri The uri of the piNFT. royalties The royalties being set for the token/
function lazyMintNFT( address _to, string memory _uri, LibShare.Share[] memory royalties ) external whenNotPaused returns (uint256) { require(isTrustedForwarder(msg.sender)); return mintNFT(_to, _uri, royalties); }
5,034,296
./full_match/1/0x5E57C528EF9126200D76620e7b843600635E74Ca/sources/sir-token.sol
Other networks will not "know" if it's enabled or disabled. We need ability to disable or re-enable autobuybackandburn. If something goes wrong it can also be turned on/off manually by the contract owner, but can be re-enabled only on main net; it will be auto disabled if total supply is equal or less then max burn Requires if value_ is true: - Total of burned tokens must be less than Max.burn var - isMainNet is true eg. we have to be on ethereum mainnet Emits: {AutoBuyBackAndBurnEnabled} bool value_/
function setAutoBuyBackAndBurn( bool value_ ) external onlyOwner { if (value_) { require(Total.burned < Max.burn, "18"); require(Bool.isMainNet, "19"); Tax[0xA0].enabled = Tax[0xA0].pState; Tax[0xA0].percent = Tax[0xA0].pPercent; Tax[0xA1].enabled = Tax[0xA1].pState; Tax[0xA1].percent = Tax[0xA1].pPercent; Bool.buyBack = true; } if (!value_ && Bool.buyBack) cleanUpAndEndTheBurn(); emit AutoBuyBackAndBurnEnabled(value_); }
17,066,131
./full_match/3/0x109d2FC653EeD5Ecc5c2213CfC683F1D81D0303d/sources/contracts/token/ERC721/Tatum721.sol
checking cashback addresses exists and sum of cashbacks transferring cashback to authors
function transferWithCashback(address to, uint256 tokenId) public payable { require(_cashbacks[tokenId].length!=0, "CashbackToken should be of cashback type"); require(_cashbackBalance(tokenId) < msg.value, "Value should be greater than or equal to cashback value"); for (uint i=0;i<_cashbacks[tokenId].length;i++){ payable(_cashbacks[tokenId][i]).transfer(_cashbacksValue[tokenId][i]); } safeTransferFrom(_msgSender(), to, tokenId, ""); }
14,185,806
./full_match/5/0x5658F3E40Cd4F73964B712D9F77a4fc15AE66Cb0/sources/contracts/certificate.sol
NFTs are non-tradeable, non-sellable, and non-transferable Keep track of total NFTs issued Attach certificate data to NFT Attach image data to NFT
function mintNFT( address to, string memory certName, string memory certCompany, string memory imageURI ) external { require(msg.sender == owner, "Caller is not owner"); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _safeMint(to, newItemId); _setTokenURI(newItemId, ""); _accountTokens[to].push(newItemId); _certNames[newItemId] = certName; _certCompany[newItemId] = certCompany; _imageURIs[newItemId] = imageURI; }
7,083,548
pragma solidity ^0.4.18; contract CrowdsaleParameters { /////////////////////////////////////////////////////////////////////////// // Production Config /////////////////////////////////////////////////////////////////////////// // ICO period timestamps: // 1524182400 = April 20, 2018. // 1529452800 = June 20, 2018. uint256 public constant generalSaleStartDate = 1524182400; uint256 public constant generalSaleEndDate = 1529452800; /////////////////////////////////////////////////////////////////////////// // QA Config /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Configuration Independent Parameters /////////////////////////////////////////////////////////////////////////// struct AddressTokenAllocation { address addr; uint256 amount; } AddressTokenAllocation internal generalSaleWallet = AddressTokenAllocation(0x5aCdaeF4fa410F38bC26003d0F441d99BB19265A, 22800000); AddressTokenAllocation internal bounty = AddressTokenAllocation(0xc1C77Ff863bdE913DD53fD6cfE2c68Dfd5AE4f7F, 2000000); AddressTokenAllocation internal partners = AddressTokenAllocation(0x307744026f34015111B04ea4D3A8dB9FdA2650bb, 3200000); AddressTokenAllocation internal team = AddressTokenAllocation(0xCC4271d219a2c33a92aAcB4C8D010e9FBf664D1c, 12000000); AddressTokenAllocation internal featureDevelopment = AddressTokenAllocation(0x06281A31e1FfaC1d3877b29150bdBE93073E043B, 0); } contract Owned { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * Constructor * * Sets contract owner to address of constructor caller */ function Owned() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } /** * Change Owner * * Changes ownership of this contract. Only owner can call this method. * * @param newOwner - new owner's address */ function changeOwner(address newOwner) onlyOwner public { require(newOwner != address(0)); require(newOwner != owner); OwnershipTransferred(owner, newOwner); owner = newOwner; } } 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; } } contract SBIToken is Owned, CrowdsaleParameters { using SafeMath for uint256; /* Public variables of the token */ string public standard = 'ERC20/SBI'; string public name = 'Subsoil Blockchain Investitions'; string public symbol = 'SBI'; uint8 public decimals = 18; /* Arrays of all balances */ mapping (address => uint256) private balances; mapping (address => mapping (address => uint256)) private allowed; mapping (address => mapping (address => bool)) private allowanceUsed; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Issuance(uint256 _amount); // triggered when the total supply is increased event Destruction(uint256 _amount); // triggered when the total supply is decreased event NewSBIToken(address _token); /* Miscellaneous */ uint256 public totalSupply = 0; // 40000000; bool public transfersEnabled = true; /** * Constructor * * Initializes contract with initial supply tokens to the creator of the contract */ function SBIToken() public { owner = msg.sender; mintToken(generalSaleWallet); mintToken(bounty); mintToken(partners); mintToken(team); NewSBIToken(address(this)); } modifier transfersAllowed { require(transfersEnabled); _; } modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } /** * 1. Associate crowdsale contract address with this Token * 2. Allocate general sale amount * * @param _crowdsaleAddress - crowdsale contract address */ function approveCrowdsale(address _crowdsaleAddress) external onlyOwner { approveAllocation(generalSaleWallet, _crowdsaleAddress); } function approveAllocation(AddressTokenAllocation tokenAllocation, address _crowdsaleAddress) internal { uint uintDecimals = decimals; uint exponent = 10**uintDecimals; uint amount = tokenAllocation.amount * exponent; allowed[tokenAllocation.addr][_crowdsaleAddress] = amount; Approval(tokenAllocation.addr, _crowdsaleAddress, amount); } /** * Get token balance of an address * * @param _address - address to query * @return Token balance of _address */ function balanceOf(address _address) public constant returns (uint256 balance) { return balances[_address]; } /** * Get token amount allocated for a transaction from _owner to _spender addresses * * @param _owner - owner address, i.e. address to transfer from * @param _spender - spender address, i.e. address to transfer to * @return Remaining amount allowed to be transferred */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * Send coins from sender's address to address specified in parameters * * @param _to - address to send to * @param _value - amount to send in Wei */ function transfer(address _to, uint256 _value) public transfersAllowed onlyPayloadSize(2*32) returns (bool success) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * Create token and credit it to target address * Created tokens need to vest * */ function mintToken(AddressTokenAllocation tokenAllocation) internal { uint uintDecimals = decimals; uint exponent = 10**uintDecimals; uint mintedAmount = tokenAllocation.amount * exponent; // Mint happens right here: Balance becomes non-zero from zero balances[tokenAllocation.addr] += mintedAmount; totalSupply += mintedAmount; // Emit Issue and Transfer events Issuance(mintedAmount); Transfer(address(this), tokenAllocation.addr, mintedAmount); } /** * Allow another contract to spend some tokens on your behalf * * @param _spender - address to allocate tokens for * @param _value - number of tokens to allocate * @return True in case of success, otherwise false */ function approve(address _spender, uint256 _value) public onlyPayloadSize(2*32) returns (bool success) { require(_value == 0 || allowanceUsed[msg.sender][_spender] == false); allowed[msg.sender][_spender] = _value; allowanceUsed[msg.sender][_spender] = false; Approval(msg.sender, _spender, _value); return true; } /** * A contract attempts to get the coins. Tokens should be previously allocated * * @param _to - address to transfer tokens to * @param _from - address to transfer tokens from * @param _value - number of tokens to transfer * @return True in case of success, otherwise false */ function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed onlyPayloadSize(3*32) returns (bool success) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * Default method * * This unnamed function is called whenever someone tries to send ether to * it. Just revert transaction because there is nothing that Token can do * with incoming ether. * * Missing payable modifier prevents accidental sending of ether */ function() public {} /** * Enable or disable transfers * * @param _enable - True = enable, False = disable */ function toggleTransfers(bool _enable) external onlyOwner { transfersEnabled = _enable; } }
1. Associate crowdsale contract address with this Token 2. Allocate general sale amount _crowdsaleAddress - crowdsale contract address/
function approveCrowdsale(address _crowdsaleAddress) external onlyOwner { approveAllocation(generalSaleWallet, _crowdsaleAddress); }
1,316,814
// SPDX-License-Identifier: MIT /* A simple gauge contract to measure the amount of tokens locked, and reward users in a different token. This Gauge works for a "sharesOf" based rebalance token. */ pragma solidity ^0.6.11; /* * @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 Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev 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 () 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; } } /** * @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; } } /** * @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); } /** * @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"); } } } interface IFarmTokenV1 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function getSharesForUnderlying(uint256 _amountUnderlying) external view returns (uint256); function getUnderlyingForShares(uint256 _amountShares) external view returns (uint256); } contract GaugeD2_USDC is IERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address payable public governance = 0xdD7A75CC6c04031629f13848Bc0D07e89C3961Be; // STACK DAO Council Multisig address public constant acceptToken = 0x067b9FE006E16f52BBf647aB6799f87566480D2c; // stackToken USDC rebase token address public constant STACK = 0xe0955F26515d22E347B17669993FCeFcc73c3a0a; // STACK DAO Token uint256 public emissionRate = 16806186020950591; uint256 public depositedShares; uint256 public constant startBlock = 12234861; uint256 public endBlock = startBlock + 1190038; uint256 public lastBlock; // last block the distribution has ran uint256 public tokensAccrued; // tokens to distribute per weight scaled by 1e18 struct DepositState { uint256 userShares; uint256 tokensAccrued; } mapping(address => DepositState) public shares; event Deposit(address indexed from, uint256 amount); event Withdraw(address indexed to, uint256 amount); event STACKClaimed(address indexed to, uint256 amount); // emit mint/burn on deposit/withdraw event Transfer(address indexed from, address indexed to, uint256 value); // never emitted, only included here to align with ERC20 spec. event Approval(address indexed owner, address indexed spender, uint256 value); constructor() public { } function setGovernance(address payable _new) external { require(msg.sender == governance); governance = _new; } function setEmissionRate(uint256 _new) external { require(msg.sender == governance, "GAUGED2: !governance"); _kick(); // catch up the contract to the current block for old rate emissionRate = _new; } function setEndBlock(uint256 _block) external { require(msg.sender == governance, "GAUGED2: !governance"); require(block.number <= endBlock, "GAUGED2: distribution already done, must start another"); require(block.number <= _block, "GAUGED2: can't set endBlock to past block"); endBlock = _block; } /////////// NOTE: Our gauges now implement mock ERC20 functionality in order to interact nicer with block explorers... function name() external view returns (string memory){ return string(abi.encodePacked("gauge-", IFarmTokenV1(acceptToken).name())); } function symbol() external view returns (string memory){ return string(abi.encodePacked("gauge-", IFarmTokenV1(acceptToken).symbol())); } function decimals() external view returns (uint8){ return IFarmTokenV1(acceptToken).decimals(); } function totalSupply() external override view returns (uint256){ return IFarmTokenV1(acceptToken).getUnderlyingForShares(depositedShares); } function balanceOf(address _account) public override view returns (uint256){ return IFarmTokenV1(acceptToken).getUnderlyingForShares(shares[_account].userShares); } // transfer tokens, not shares function transfer(address _recipient, uint256 _amount) external override returns (bool){ // to squelch _recipient; _amount; revert("transfer not implemented. please withdraw first."); } function transferFrom(address _sender, address _recipient, uint256 _amount) external override returns (bool){ // to squelch _sender; _recipient; _amount; revert("transferFrom not implemented. please withdraw first."); } // allow tokens, not shares function allowance(address _owner, address _spender) external override view returns (uint256){ // to squelch _owner; _spender; return 0; } // approve tokens, not shares function approve(address _spender, uint256 _amount) external override returns (bool){ // to squelch _spender; _amount; revert("approve not implemented. please withdraw first."); } ////////// END MOCK ERC20 FUNCTIONALITY ////////// function deposit(uint256 _amount) nonReentrant external { require(block.number <= endBlock, "GAUGED2: distribution over"); _claimSTACK(msg.sender); // trusted contracts IERC20(acceptToken).safeTransferFrom(msg.sender, address(this), _amount); uint256 _sharesFor = IFarmTokenV1(acceptToken).getSharesForUnderlying(_amount); DepositState memory _state = shares[msg.sender]; _state.userShares = _state.userShares.add(_sharesFor); depositedShares = depositedShares.add(_sharesFor); emit Deposit(msg.sender, _amount); emit Transfer(address(0), msg.sender, _amount); shares[msg.sender] = _state; } function withdraw(uint256 _amount) nonReentrant external { _claimSTACK(msg.sender); DepositState memory _state = shares[msg.sender]; uint256 _sharesFor = IFarmTokenV1(acceptToken).getSharesForUnderlying(_amount); require(_sharesFor <= _state.userShares, "GAUGED2: insufficient balance"); _state.userShares = _state.userShares.sub(_sharesFor); depositedShares = depositedShares.sub(_sharesFor); emit Withdraw(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); shares[msg.sender] = _state; IERC20(acceptToken).safeTransfer(msg.sender, _amount); } function claimSTACK() nonReentrant external returns (uint256) { return _claimSTACK(msg.sender); } function _claimSTACK(address _user) internal returns (uint256) { _kick(); DepositState memory _state = shares[_user]; if (_state.tokensAccrued == tokensAccrued){ // user doesn't have any accrued tokens return 0; } else { uint256 _tokensAccruedDiff = tokensAccrued.sub(_state.tokensAccrued); uint256 _tokensGive = _tokensAccruedDiff.mul(_state.userShares).div(1e18); _state.tokensAccrued = tokensAccrued; shares[_user] = _state; // if the guage has enough tokens to grant the user, then send their tokens // otherwise, don't fail, just log STACK claimed, and a reimbursement can be done via chain events if (IERC20(STACK).balanceOf(address(this)) >= _tokensGive){ IERC20(STACK).safeTransfer(_user, _tokensGive); } // log event emit STACKClaimed(_user, _tokensGive); return _tokensGive; } } function _kick() internal { uint256 _totalDeposited = depositedShares; // if there are no tokens committed, then don't kick. if (_totalDeposited == 0){ return; } // already done for this block || already did all blocks || not started yet if (lastBlock == block.number || lastBlock >= endBlock || block.number < startBlock){ return; } uint256 _deltaBlock; // edge case where kick was not called for entire period of blocks. if (lastBlock <= startBlock && block.number >= endBlock){ _deltaBlock = endBlock.sub(startBlock); } // where block.number is past the endBlock else if (block.number >= endBlock){ _deltaBlock = endBlock.sub(lastBlock); } // where last block is before start else if (lastBlock <= startBlock){ _deltaBlock = block.number.sub(startBlock); } // normal case, where we are in the middle of the distribution else { _deltaBlock = block.number.sub(lastBlock); } uint256 _tokensToAccrue = _deltaBlock.mul(emissionRate); tokensAccrued = tokensAccrued.add(_tokensToAccrue.mul(1e18).div(_totalDeposited)); // if not allowed to mint it's just like the emission rate = 0. So just update the lastBlock. // always update last block lastBlock = block.number; } // decentralized rescue function for any stuck tokens, will return to governance function rescue(address _token, uint256 _amount) nonReentrant external { require(msg.sender == governance, "GAUGED2: !governance"); if (_token != address(0)){ IERC20(_token).safeTransfer(governance, _amount); } else { // if _tokenContract is 0x0, then escape ETH governance.transfer(_amount); } } }
allow tokens, not shares to squelch
function allowance(address _owner, address _spender) external override view returns (uint256){ _owner; _spender; return 0; }
1,369,346
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.7.5; import "../types/Ownable.sol"; import "../libraries/SafeMath.sol"; import "../libraries/SafeERC20.sol"; import "../libraries/FixedPoint.sol"; import "../interfaces/ITreasury.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IHelper.sol"; import "hardhat/console.sol"; contract CustomBond is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMath for uint256; event BondCreated(uint256 deposit, uint256 payout, uint256 expires); event BondRedeemed(address recipient, uint256 payout, uint256 remaining); event BondPriceChanged(uint256 internalPrice, uint256 debtRatio); event ControlVariableAdjustment(uint256 initialBCV, uint256 newBCV, uint256 adjustment, bool addition); event LPAdded(address lpAddress, uint256 lpAmount); IERC20 public immutable PAYOUT_TOKEN; // token paid for principal IERC20 public immutable PRINCIPAL_TOKEN; // inflow token ITreasury public immutable CUSTOM_TREASURY; // pays for and receives principal address public immutable DAO; address public immutable SUBSIDY_ROUTER; // pays subsidy in TAO to custom treasury address public OLY_TREASURY; // receives fee address public immutable HELPER; // helper for helping swap, lend to get lp token uint256 public totalPrincipalBonded; uint256 public totalPayoutGiven; uint256 public totalDebt; // total value of outstanding bonds; used for pricing uint256 public lastDecay; // reference block for debt decay uint256 public payoutSinceLastSubsidy; // principal accrued since subsidy paid Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data FeeTiers[] private feeTiers; // stores fee tiers bool public lpTokenAsFeeFlag;// bool public bondWithOneAssetFlag; mapping(address => Bond) public bondInfo; // stores bond information for depositors struct FeeTiers { uint256 tierCeilings; // principal bonded till next tier uint256 fees; // in ten-thousandths (i.e. 33300 = 3.33%) } // Info for creating new bonds struct Terms { uint256 controlVariable; // scaling variable for price uint256 vestingTerm; // in blocks uint256 minimumPrice; // vs principal value uint256 maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint256 maxDebt; // payout token decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint256 payout; // payout token remaining to be paid uint256 vesting; // Blocks left to vest uint256 lastBlock; // Last interaction uint256 truePricePaid; // Price paid (principal tokens per payout token) in ten-millionths - 4000000 = 0.4 } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint256 rate; // increment uint256 target; // BCV when adjustment finished uint256 buffer; // minimum length (in blocks) between adjustments uint256 lastBlock; // block when last adjustment made } receive() external payable {} constructor( address _customTreasury, address _payoutToken, address _principalToken, address _olyTreasury, address _subsidyRouter, address _initialOwner, address _dao, address _helper, uint256[] memory _tierCeilings, uint256[] memory _fees ) { require(_customTreasury != address(0), "Factory: customTreasury must not be zero address"); CUSTOM_TREASURY = ITreasury(_customTreasury); require(_payoutToken != address(0), "Factory: payoutToken must not be zero address"); PAYOUT_TOKEN = IERC20(_payoutToken); require(_principalToken != address(0), "Factory: principalToken must not be zero address"); PRINCIPAL_TOKEN = IERC20(_principalToken); require(_olyTreasury != address(0), "Factory: olyTreasury must not be zero address"); OLY_TREASURY = _olyTreasury; require(_subsidyRouter != address(0), "Factory: subsidyRouter must not be zero address"); SUBSIDY_ROUTER = _subsidyRouter; require(_initialOwner != address(0), "Factory: initialOwner must not be zero address"); policy = _initialOwner; require(_dao != address(0), "Factory: DAO must not be zero address"); DAO = _dao; require(_helper != address(0), "Factory: helper must not be zero address"); HELPER = _helper; require(_tierCeilings.length == _fees.length, "tier length and fee length not the same"); for (uint256 i; i < _tierCeilings.length; i++) { feeTiers.push(FeeTiers({tierCeilings: _tierCeilings[i], fees: _fees[i]})); } lpTokenAsFeeFlag = true; } /* ======== INITIALIZATION ======== */ /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBond( uint256 _controlVariable, uint256 _vestingTerm, uint256 _minimumPrice, uint256 _maxPayout, uint256 _maxDebt, uint256 _initialDebt ) external onlyPolicy { require(currentDebt() == 0, "Debt must be 0 for initialization"); terms = Terms({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = block.number; } /** * @notice set control variable adjustment * @param _lpTokenAsFeeFlag bool */ function setLPtokenAsFee(bool _lpTokenAsFeeFlag) external onlyPolicy { lpTokenAsFeeFlag = _lpTokenAsFeeFlag; } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms(PARAMETER _parameter, uint256 _input) external onlyPolicy { if (_parameter == PARAMETER.VESTING) {// 0 require(_input >= 10000, "Vesting must be longer than 36 hours"); terms.vestingTerm = _input; } else if (_parameter == PARAMETER.PAYOUT) {// 1 require(_input <= 1000, "Payout cannot be above 1 percent"); terms.maxPayout = _input; } else if (_parameter == PARAMETER.DEBT) {// 2 terms.maxDebt = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment( bool _addition, uint256 _increment, uint256 _target, uint256 _buffer ) external onlyPolicy { require(_increment <= terms.controlVariable.mul(30).div(1000), "Increment too large"); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastBlock: block.number }); } /** * @notice change address of Treasury * @param _olyTreasury uint */ function changeOlyTreasury(address _olyTreasury) external { require(msg.sender == DAO, "changeOlyTreasury: Only DAO can replace OLY_TREASURY"); OLY_TREASURY = _olyTreasury; } /** * @notice subsidy controller checks payouts since last subsidy and resets counter * @return payoutSinceLastSubsidy_ uint */ function paySubsidy() external returns (uint256 payoutSinceLastSubsidy_) { require(msg.sender == SUBSIDY_ROUTER, "Only subsidy controller"); payoutSinceLastSubsidy_ = payoutSinceLastSubsidy; payoutSinceLastSubsidy = 0; } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint256 _amount, uint256 _maxPrice, address _depositor ) external returns (uint256) { require(_depositor != address(0), "Invalid address"); decayDebt(); require(totalDebt <= terms.maxDebt, "Max capacity reached"); uint256 nativePrice = trueBondPrice(); require(_maxPrice >= nativePrice, "Slippage limit: more than max price"); // slippage protection uint256 value = CUSTOM_TREASURY.valueOfToken(address(PRINCIPAL_TOKEN), _amount); uint256 payout = _payoutFor(value); // payout to bonder is computed require(payout >= 10**PAYOUT_TOKEN.decimals() / 100, "Bond too small"); // must be > 0.01 payout token ( underflow protection ) require(payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** principal is transferred in approved and deposited into the treasury, returning (_amount - profit) payout token */ PRINCIPAL_TOKEN.safeTransferFrom(msg.sender, address(this), _amount); // profits are calculated uint256 fee; /** principal is been taken as fee and trasfered to dao */ if (lpTokenAsFeeFlag) { fee = _amount.mul(currentFluxFee()).div(1e6); if (fee != 0) { PRINCIPAL_TOKEN.transfer(OLY_TREASURY, fee); } } else { fee = payout.mul(currentFluxFee()).div(1e6); } PRINCIPAL_TOKEN.approve(address(CUSTOM_TREASURY), _amount); CUSTOM_TREASURY.deposit(address(PRINCIPAL_TOKEN), _amount.sub(fee), payout); if (!lpTokenAsFeeFlag && fee != 0) { // fee is transferred to dao PAYOUT_TOKEN.transfer(OLY_TREASURY, fee); } // total debt is increased totalDebt = totalDebt.add(value); // depositor info is stored if(lpTokenAsFeeFlag){ bondInfo[_depositor] = Bond({ payout: bondInfo[_depositor].payout.add(payout), vesting: terms.vestingTerm, lastBlock: block.number, truePricePaid: trueBondPrice() }); } else { bondInfo[_depositor] = Bond({ payout: bondInfo[_depositor].payout.add(payout.sub(fee)), vesting: terms.vestingTerm, lastBlock: block.number, truePricePaid: trueBondPrice() }); } // indexed events are emitted emit BondCreated(_amount, payout, block.number.add(terms.vestingTerm)); emit BondPriceChanged(_bondPrice(), debtRatio()); totalPrincipalBonded = totalPrincipalBonded.add(_amount); // total bonded increased totalPayoutGiven = totalPayoutGiven.add(payout); // total payout increased payoutSinceLastSubsidy = payoutSinceLastSubsidy.add(payout); // subsidy counter increased adjust(); // control variable is adjusted return payout; } /** * @notice deposit bond with an asset(i.e: USDT) * @param _depositAmount amount of deposit asset * @param _depositAsset deposit asset * @param _incomingAsset asset address for swap from deposit asset * @param _depositor address of depositor * @return uint */ function depositWithAsset( uint256 _depositAmount, address _depositAsset, address _incomingAsset, address _depositor ) external returns (uint256) { require(_depositor != address(0), "depositWithAsset: Invalid address"); (address lpAddress, uint256 lpAmount) = __lpAddressAndAmount(_depositAmount, _depositAsset, _incomingAsset); console.log("==sol-lp-payout-0::", IERC20(lpAddress).balanceOf(address(this)), PAYOUT_TOKEN.balanceOf(address(this))); // remain payoutToken is transferred to user __transferAssetToCaller(msg.sender, address(PAYOUT_TOKEN)); require(lpAddress != address(0), "depositWithAsset: Invalid incoming asset"); require(lpAmount > 0, "depositWithAsset: Insufficient lpAmount"); decayDebt(); require(totalDebt <= terms.maxDebt, "depositWithAsset: Max capacity reached"); uint256 nativePrice = trueBondPrice(); // require(_maxPrice >= nativePrice, "Slippage limit: more than max price"); // slippage protection uint256 value = CUSTOM_TREASURY.valueOfToken(lpAddress, lpAmount); uint256 payout = _payoutFor(value); // payout to bonder is computed require(payout >= 10**PAYOUT_TOKEN.decimals() / 100, "Bond too small"); // must be > 0.01 payout token ( underflow protection ) require(payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // profits are calculated uint256 fee; /** principal is been taken as fee and trasfered to dao */ if (lpTokenAsFeeFlag) { fee = lpAmount.mul(currentFluxFee()).div(1e6); if (fee != 0) { IERC20(lpAddress).transfer(OLY_TREASURY, fee);// fee is transferred to dao as LP } } else { fee = payout.mul(currentFluxFee()).div(1e6); } IERC20(lpAddress).approve(address(CUSTOM_TREASURY), lpAmount); CUSTOM_TREASURY.deposit(lpAddress, lpAmount.sub(fee), payout); if (!lpTokenAsFeeFlag && fee != 0) { // fee is transferred to dao as payoutToken PAYOUT_TOKEN.transfer(OLY_TREASURY, fee); } // total debt is increased totalDebt = totalDebt.add(value); // depositor info is stored if(lpTokenAsFeeFlag){ bondInfo[_depositor] = Bond({ payout: bondInfo[_depositor].payout.add(payout), vesting: terms.vestingTerm, lastBlock: block.number, truePricePaid: trueBondPrice() }); } else { bondInfo[_depositor] = Bond({ payout: bondInfo[_depositor].payout.add(payout.sub(fee)), vesting: terms.vestingTerm, lastBlock: block.number, truePricePaid: trueBondPrice() }); } // indexed events are emitted emit BondCreated(lpAmount, payout, block.number.add(terms.vestingTerm)); emit BondPriceChanged(_bondPrice(), debtRatio()); totalPrincipalBonded = totalPrincipalBonded.add(lpAmount); // total bonded increased totalPayoutGiven = totalPayoutGiven.add(payout); // total payout increased payoutSinceLastSubsidy = payoutSinceLastSubsidy.add(payout); // subsidy counter increased adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @return uint */ function redeem(address _depositor) external returns (uint) { Bond memory info = bondInfo[_depositor]; uint percentVested = percentVestedFor(_depositor); // (blocks since last interaction / vesting term remaining) if (percentVested >= 10000) { // if fully vested delete bondInfo[_depositor]; // delete user info emit BondRedeemed(_depositor, info.payout, 0); // emit bond data if(info.payout > 0) { PAYOUT_TOKEN.transfer(_depositor, info.payout); } return info.payout; } else { // if unfinished // calculate payout vested uint256 payout = info.payout.mul(percentVested).div(10000); // store updated deposit info bondInfo[_depositor] = Bond({ payout: info.payout.sub(payout), vesting: info.vesting.sub(block.number.sub(info.lastBlock)), lastBlock: block.number, truePricePaid: info.truePricePaid }); emit BondRedeemed(_depositor, payout, bondInfo[_depositor].payout); if(payout > 0) { PAYOUT_TOKEN.transfer(_depositor, payout); } return payout; } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint256 blockCanAdjust = adjustment.lastBlock.add(adjustment.buffer); if (adjustment.rate != 0 && block.number >= blockCanAdjust) { uint256 initial = terms.controlVariable; if (adjustment.add) { terms.controlVariable = terms.controlVariable.add(adjustment.rate); if (terms.controlVariable >= adjustment.target) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub(adjustment.rate); if (terms.controlVariable <= adjustment.target) { adjustment.rate = 0; } } adjustment.lastBlock = block.number; emit ControlVariableAdjustment(initial, terms.controlVariable, adjustment.rate, adjustment.add); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub(debtDecay()); lastDecay = block.number; } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns (uint256 price_) { price_ = terms.controlVariable.mul(debtRatio()).div(10**(uint256(PAYOUT_TOKEN.decimals()).sub(5))); if (price_ < terms.minimumPrice) { price_ = terms.minimumPrice; } else if (terms.minimumPrice != 0) { terms.minimumPrice = 0; } } /* ======== VIEW FUNCTIONS ======== */ /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns (uint256 price_) { price_ = terms.controlVariable.mul(debtRatio()).div(10**(uint256(PAYOUT_TOKEN.decimals()).sub(5))); if (price_ < terms.minimumPrice) { price_ = terms.minimumPrice; } } /** * @notice calculate true bond price a user pays * @return price_ uint */ function trueBondPrice() public view returns (uint256 price_) { price_ = bondPrice().add(bondPrice().mul(currentFluxFee()).div(1e6)); } /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns (uint) { uint256 totalSupply = PAYOUT_TOKEN.totalSupply(); if(totalSupply > 10**18) totalSupply = 10**18; return totalSupply.mul(terms.maxPayout).div(100000); } /** * @notice calculate total interest due for new bond * @param _value uint * @return uint */ function _payoutFor(uint256 _value) internal view returns (uint256) { return FixedPoint.fraction(_value, bondPrice()).decode112with18().div(1e11); } /** * @notice calculate user's interest due for new bond, accounting for Flux Fee * @param _value uint * @return uint */ function payoutFor(uint256 _value) external view returns (uint256) { uint256 total = FixedPoint.fraction(_value, bondPrice()).decode112with18().div(1e11); return total.sub(total.mul(currentFluxFee()).div(1e6)); } /** * @notice calculate current ratio of debt to payout token supply * @notice protocols using Flux Pro should be careful when quickly adding large %s to total supply * @return debtRatio_ uint */ function debtRatio() public view returns (uint256 debtRatio_) { debtRatio_ = FixedPoint .fraction(currentDebt().mul(10**PAYOUT_TOKEN.decimals()), PAYOUT_TOKEN.totalSupply()) .decode112with18() .div(1e18); } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns (uint256) { return totalDebt.sub(debtDecay()); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns (uint256 decay_) { uint256 blocksSinceLast = block.number.sub(lastDecay); decay_ = totalDebt.mul(blocksSinceLast).div(terms.vestingTerm); if (decay_ > totalDebt) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor(address _depositor) public view returns (uint256 percentVested_) { Bond memory bond = bondInfo[_depositor]; uint256 blocksSinceLast = block.number.sub(bond.lastBlock); uint256 vesting = bond.vesting; if (vesting > 0) { percentVested_ = blocksSinceLast.mul(10000).div(vesting); } else { percentVested_ = 0; } } /** * @notice calculate amount of payout token available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor(address _depositor) external view returns (uint256 pendingPayout_) { uint256 percentVested = percentVestedFor(_depositor); uint256 payout = bondInfo[_depositor].payout; if (percentVested >= 10000) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul(percentVested).div(10000); } } /** * @notice current fee Flux takes of each bond * @return currentFee_ uint */ function currentFluxFee() public view returns (uint256 currentFee_) { uint256 tierLength = feeTiers.length; for (uint256 i; i < tierLength; i++) { if (totalPrincipalBonded < feeTiers[i].tierCeilings || i == tierLength - 1) { return feeTiers[i].fees; } } } /// @dev Helper to transfer full contract balances of assets to the caller function __transferAssetToCaller(address _target, address _asset) private { uint256 transferAmount = IERC20(_asset).balanceOf(address(this)); if (transferAmount > 0) { IERC20(_asset).safeTransfer(_target, transferAmount); } } /// @notice Swap and AddLiquidity on the UniswapV2 function __lpAddressAndAmount( uint256 _depositAmount, address _depositAsset, address _incomingAsset ) public payable returns (address lpAddress_, uint256 lpAmount_) { if(_depositAsset == address(0)) { payable(address(HELPER)).transfer(address(this).balance); } else { IERC20(_depositAsset).safeTransferFrom(msg.sender, address(this), _depositAmount); IERC20(_depositAsset).approve(address(HELPER), _depositAmount); } bytes memory swapArgs = abi.encode(_depositAmount, _depositAsset, address(PAYOUT_TOKEN), _incomingAsset); (lpAddress_, lpAmount_) = IHelper(HELPER).swapForDeposit(swapArgs); emit LPAdded(lpAddress_, lpAmount_); } }
Helper to transfer full contract balances of assets to the caller
function __transferAssetToCaller(address _target, address _asset) private { uint256 transferAmount = IERC20(_asset).balanceOf(address(this)); if (transferAmount > 0) { IERC20(_asset).safeTransfer(_target, transferAmount); } }
12,625,485
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul interface DharmaTradeReserveV15Interface { event Trade( address account, address suppliedAsset, address receivedAsset, address retainedAsset, uint256 suppliedAmount, uint256 recievedAmount, uint256 retainedAmount ); event RoleModified(Role indexed role, address account); event RolePaused(Role indexed role); event RoleUnpaused(Role indexed role); event EtherReceived(address sender, uint256 amount); event GasReserveRefilled(uint256 etherAmount); enum Role { // # DEPOSIT_MANAGER, // 0 ADJUSTER, // 1 WITHDRAWAL_MANAGER, // 2 RESERVE_TRADER, // 3 PAUSER, // 4 GAS_RESERVE_REFILLER // 5 } enum TradeType { DAI_TO_TOKEN, DAI_TO_ETH, ETH_TO_DAI, TOKEN_TO_DAI, ETH_TO_TOKEN, TOKEN_TO_ETH, TOKEN_TO_TOKEN } struct RoleStatus { address account; bool paused; } function tradeDaiForEtherV2( uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function tradeEtherForDaiV2( uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought); function tradeDaiForToken( address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold); function tradeTokenForDai( ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought); function tradeTokenForEther( ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought); function tradeEtherForToken( address token, uint256 quotedTokenAmount, uint256 deadline ) external payable returns (uint256 totalEtherSold); function tradeEtherForTokenUsingEtherizer( address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold); function tradeTokenForToken( ERC20Interface tokenProvided, address tokenReceived, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensSold); function tradeTokenForTokenUsingReserves( ERC20Interface tokenProvidedFromReserves, address tokenReceived, uint256 tokenProvidedAmountFromReserves, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensSold); function tradeDaiForEtherUsingReservesV2( uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function tradeEtherForDaiUsingReservesAndMintDDaiV2( uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted); function tradeDaiForTokenUsingReserves( address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold); function tradeTokenForDaiUsingReservesAndMintDDai( ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted); function tradeTokenForEtherUsingReserves( ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought); function tradeEtherForTokenUsingReserves( address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold); function finalizeEtherDeposit( address payable smartWallet, address initialUserSigningKey, uint256 etherAmount ) external; function finalizeDaiDeposit( address smartWallet, address initialUserSigningKey, uint256 daiAmount ) external; function finalizeDharmaDaiDeposit( address smartWallet, address initialUserSigningKey, uint256 dDaiAmount ) external; function mint(uint256 daiAmount) external returns (uint256 dDaiMinted); function redeem(uint256 dDaiAmount) external returns (uint256 daiReceived); function tradeDDaiForUSDC( uint256 daiEquivalentAmount, uint256 quotedUSDCAmount ) external returns (uint256 usdcReceived); function tradeUSDCForDDai( uint256 usdcAmount, uint256 quotedDaiEquivalentAmount ) external returns (uint256 dDaiMinted); function refillGasReserve(uint256 etherAmount) external; function withdrawUSDC(address recipient, uint256 usdcAmount) external; function withdrawDai(address recipient, uint256 daiAmount) external; function withdrawDharmaDai(address recipient, uint256 dDaiAmount) external; function withdrawUSDCToPrimaryRecipient(uint256 usdcAmount) external; function withdrawDaiToPrimaryRecipient(uint256 usdcAmount) external; function withdrawEther( address payable recipient, uint256 etherAmount ) external; function withdraw( ERC20Interface token, address recipient, uint256 amount ) external returns (bool success); function callAny( address payable target, uint256 amount, bytes calldata data ) external returns (bool ok, bytes memory returnData); function setDaiLimit(uint256 daiAmount) external; function setEtherLimit(uint256 daiAmount) external; function setPrimaryUSDCRecipient(address recipient) external; function setPrimaryDaiRecipient(address recipient) external; function setRole(Role role, address account) external; function removeRole(Role role) external; function pause(Role role) external; function unpause(Role role) external; function isPaused(Role role) external view returns (bool paused); function isRole(Role role) external view returns (bool hasRole); function isDharmaSmartWallet( address smartWallet, address initialUserSigningKey ) external view returns (bool dharmaSmartWallet); function getDepositManager() external view returns (address depositManager); function getAdjuster() external view returns (address adjuster); function getReserveTrader() external view returns (address reserveTrader); function getWithdrawalManager() external view returns (address withdrawalManager); function getPauser() external view returns (address pauser); function getGasReserveRefiller() external view returns (address gasReserveRefiller); function getReserves() external view returns ( uint256 dai, uint256 dDai, uint256 dDaiUnderlying ); function getDaiLimit() external view returns ( uint256 daiAmount, uint256 dDaiAmount ); function getEtherLimit() external view returns (uint256 etherAmount); function getPrimaryUSDCRecipient() external view returns ( address recipient ); function getPrimaryDaiRecipient() external view returns ( address recipient ); function getImplementation() external view returns (address implementation); function getInstance() external pure returns (address instance); function getVersion() external view returns (uint256 version); } interface ERC20Interface { function balanceOf(address) external view returns (uint256); function approve(address, uint256) external returns (bool); function allowance(address, address) external view returns (uint256); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); } interface DTokenInterface { function mint(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); function redeem(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); function redeemUnderlying(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); function balanceOf(address) external view returns (uint256); function balanceOfUnderlying(address) external view returns (uint256); function transfer(address, uint256) external returns (bool); function approve(address, uint256) external returns (bool); function exchangeRateCurrent() external view returns (uint256); } interface TradeHelperInterface { function tradeUSDCForDDai( uint256 amountUSDC, uint256 quotedDaiEquivalentAmount ) external returns (uint256 dDaiMinted); function tradeDDaiForUSDC( uint256 amountDai, uint256 quotedUSDCAmount ) external returns (uint256 usdcReceived); function getExpectedDai(uint256 usdc) external view returns (uint256 dai); function getExpectedUSDC(uint256 dai) external view returns (uint256 usdc); } interface UniswapV2Interface { function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } } /** * @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. * * In order to transfer ownership, a recipient must be specified, at which point * the specified recipient can call `acceptOwnership` and take ownership. */ contract TwoStepOwnable { event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); address private _owner; address private _newPotentialOwner; /** * @dev Allows a new account (`newOwner`) to accept ownership. * Can only be called by the current owner. */ function transferOwnership(address newOwner) external onlyOwner { require( newOwner != address(0), "TwoStepOwnable: new potential owner is the zero address." ); _newPotentialOwner = newOwner; } /** * @dev Cancel a transfer of ownership to a new account. * Can only be called by the current owner. */ function cancelOwnershipTransfer() external onlyOwner { delete _newPotentialOwner; } /** * @dev Transfers ownership of the contract to the caller. * Can only be called by a new potential owner set by the current owner. */ function acceptOwnership() external { require( msg.sender == _newPotentialOwner, "TwoStepOwnable: current owner must set caller as new potential owner." ); delete _newPotentialOwner; emit OwnershipTransferred(_owner, msg.sender); _owner = msg.sender; } /** * @dev Returns the address of the current owner. */ function owner() external view returns (address) { return _owner; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "TwoStepOwnable: caller is not the owner."); _; } } /** * @title DharmaTradeReserveV15ImplementationStaging * @author 0age * @notice This contract manages Dharma's reserves. It designates a collection of * "roles" - these are dedicated accounts that can be modified by the owner, and * that can trigger specific functionality on the reserve. These roles are: * - depositManager (0): initiates Eth / token transfers to smart wallets * - adjuster (1): mints / redeems Dai, and swaps USDC, for dDai * - withdrawalManager (2): initiates token transfers to recipients set by owner * - reserveTrader (3): initiates trades using funds held in reserve * - pauser (4): pauses any role (only the owner is then able to unpause it) * - gasReserveRefiller (5): transfers Ether to the Dharma Gas Reserve * * When finalizing deposits, the deposit manager must adhere to two constraints: * - it must provide "proof" that the recipient is a smart wallet by including * the initial user signing key used to derive the smart wallet address * - it must not attempt to transfer more Eth, Dai, or the Dai-equivalent * value of Dharma Dai, than the current "limit" set by the owner. * * Note that "proofs" can be validated via `isSmartWallet`. */ contract DharmaTradeReserveV15ImplementationStaging is DharmaTradeReserveV15Interface, TwoStepOwnable { using SafeMath for uint256; // Maintain a role status mapping with assigned accounts and paused states. mapping(uint256 => RoleStatus) private _roles; // Maintain a "primary recipient" the withdrawal manager can transfer Dai to. address private _primaryDaiRecipient; // Maintain a "primary recipient" the withdrawal manager can transfer USDC to. address private _primaryUSDCRecipient; // Maintain a maximum allowable transfer size (in Dai) for the deposit manager. uint256 private _daiLimit; // Maintain a maximum allowable transfer size (in Ether) for the deposit manager. uint256 private _etherLimit; bool private _originatesFromReserveTrader; // unused, don't change storage layout uint256 private constant _VERSION = 1015; // This contract interacts with USDC, Dai, and Dharma Dai. ERC20Interface internal constant _USDC = ERC20Interface( 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet ); ERC20Interface internal constant _DAI = ERC20Interface( 0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet ); ERC20Interface internal constant _ETHERIZER = ERC20Interface( 0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191 ); DTokenInterface internal constant _DDAI = DTokenInterface( 0x00000000001876eB1444c986fD502e618c587430 ); TradeHelperInterface internal constant _TRADE_HELPER = TradeHelperInterface( 0x9328F2Fb3e85A4d24Adc2f68F82737183e85691d ); UniswapV2Interface internal constant _UNISWAP_ROUTER = UniswapV2Interface( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address internal constant _WETH = address( 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ); address internal constant _GAS_RESERVE = address( 0x09cd826D4ABA4088E1381A1957962C946520952d // staging version ); // The "Create2 Header" is used to compute smart wallet deployment addresses. bytes21 internal constant _CREATE2_HEADER = bytes21( 0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory ); // The "Wallet creation code" header & footer are also used to derive wallets. bytes internal constant _WALLET_CREATION_CODE_HEADER = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000"; bytes28 internal constant _WALLET_CREATION_CODE_FOOTER = bytes28( 0x00000000000000000000000000000000000000000000000000000000 ); // Flag to trigger trade for USDC and retain full trade amount address internal constant _TRADE_FOR_USDC_AND_RETAIN_FLAG = address(uint160(-1)); // Include a payable fallback so that the contract can receive Ether payments. function () external payable { emit EtherReceived(msg.sender, msg.value); } function initialize() external onlyOwner { // Approve Uniswap router to transfer WETH on behalf of this contract. _grantUniswapRouterApprovalIfNecessary(ERC20Interface(_WETH), uint256(-1)); } /** * @notice Pull in `daiAmount` Dai from the caller, trade it for Ether using * UniswapV2, and return `quotedEtherAmount` Ether to the caller. * @param daiAmount uint256 The amount of Dai to supply when trading for Ether. * @param quotedEtherAmount uint256 The amount of Ether to return to the caller. * @param deadline uint256 The timestamp the order is valid until. * @return The amount of Dai sold as part of the trade. */ function tradeDaiForEtherV2( uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold) { // Transfer the Dai from the caller and revert on failure. _transferInToken(_DAI, msg.sender, daiAmount); // Trade Dai for Ether. totalDaiSold = _tradeDaiForEther( daiAmount, quotedEtherAmount, deadline, false ); } function tradeTokenForEther( ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought) { // Transfer the tokens from the caller and revert on failure. _transferInToken(token, msg.sender, tokenAmount); // Trade tokens for Ether. totalEtherBought = _tradeTokenForEther( token, tokenAmount, quotedEtherAmount, deadline, false ); // Transfer the quoted Ether amount to the caller. _transferEther(msg.sender, quotedEtherAmount); } function tradeDaiForToken( address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold) { // Transfer the Dai from the caller and revert on failure. _transferInToken(_DAI, msg.sender, daiAmount); // Trade Dai for specified token. totalDaiSold = _tradeDaiForToken( token, daiAmount, quotedTokenAmount, deadline, routeThroughEther, false ); } /** * @notice Using `daiAmountFromReserves` Dai (note that dDai will be redeemed * if necessary), trade for Ether using UniswapV2. Only the owner or the trade * reserve role can call this function. Note that Dharma Dai will be redeemed * to cover the Dai if there is not enough currently in the contract. * @param daiAmountFromReserves the amount of Dai to take from reserves. * @param quotedEtherAmount uint256 The amount of Ether requested in the trade. * @param deadline uint256 The timestamp the order is valid until. * @return The amount of Ether bought as part of the trade. */ function tradeDaiForEtherUsingReservesV2( uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { // Redeem dDai if the current Dai balance is less than is required. _redeemDDaiIfNecessary(daiAmountFromReserves); // Trade Dai for Ether using reserves. totalDaiSold = _tradeDaiForEther( daiAmountFromReserves, quotedEtherAmount, deadline, true ); } function tradeTokenForEtherUsingReserves( ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalEtherBought) { // Trade tokens for Ether using reserves. totalEtherBought = _tradeTokenForEther( token, tokenAmountFromReserves, quotedEtherAmount, deadline, true ); } /** * @notice Accept `msg.value` Ether from the caller, trade it for Dai using * UniswapV2, and return `quotedDaiAmount` Dai to the caller. * @param quotedDaiAmount uint256 The amount of Dai to return to the caller. * @param deadline uint256 The timestamp the order is valid until. * @return The amount of Dai bought as part of the trade. */ function tradeEtherForDaiV2( uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought) { // Trade Ether for Dai. totalDaiBought = _tradeEtherForDai( msg.value, quotedDaiAmount, deadline, false ); // Transfer the Dai to the caller and revert on failure. _transferToken(_DAI, msg.sender, quotedDaiAmount); } function tradeEtherForToken( address token, uint256 quotedTokenAmount, uint256 deadline ) external payable returns (uint256 totalEtherSold) { // Trade Ether for the specified token. totalEtherSold = _tradeEtherForToken( token, msg.value, quotedTokenAmount, deadline, false ); } function tradeEtherForTokenUsingEtherizer( address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold) { // Transfer the Ether from the caller and revert on failure. _transferInToken(_ETHERIZER, msg.sender, etherAmount); // Trade Ether for the specified token. totalEtherSold = _tradeEtherForToken( token, etherAmount, quotedTokenAmount, deadline, false ); } function tradeTokenForDai( ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought) { // Transfer the token from the caller and revert on failure. _transferInToken(token, msg.sender, tokenAmount); // Trade the token for Dai. totalDaiBought = _tradeTokenForDai( token, tokenAmount, quotedDaiAmount, deadline, routeThroughEther, false ); // Transfer the quoted Dai amount to the caller and revert on failure. _transferToken(_DAI, msg.sender, quotedDaiAmount); } function tradeTokenForToken( ERC20Interface tokenProvided, address tokenReceived, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensSold) { // Transfer the token from the caller and revert on failure. _transferInToken(tokenProvided, msg.sender, tokenProvidedAmount); totalTokensSold = _tradeTokenForToken( msg.sender, tokenProvided, tokenReceived, tokenProvidedAmount, quotedTokenReceivedAmount, deadline, routeThroughEther ); } function tradeTokenForTokenUsingReserves( ERC20Interface tokenProvidedFromReserves, address tokenReceived, uint256 tokenProvidedAmountFromReserves, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalTokensSold) { totalTokensSold = _tradeTokenForToken( address(this), tokenProvidedFromReserves, tokenReceived, tokenProvidedAmountFromReserves, quotedTokenReceivedAmount, deadline, routeThroughEther ); } /** * @notice Using `etherAmountFromReserves`, trade for Dai using UniswapV2, * and use that Dai to mint Dharma Dai. * Only the owner or the trade reserve role can call this function. * @param etherAmountFromReserves the amount of Ether to take from reserves * and add to the provided amount. * @param quotedDaiAmount uint256 The amount of Dai requested in the trade. * @param deadline uint256 The timestamp the order is valid until. * @return The amount of Dai bought as part of the trade. */ function tradeEtherForDaiUsingReservesAndMintDDaiV2( uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external onlyOwnerOr(Role.RESERVE_TRADER) returns ( uint256 totalDaiBought, uint256 totalDDaiMinted ) { // Trade Ether for Dai using reserves. totalDaiBought = _tradeEtherForDai( etherAmountFromReserves, quotedDaiAmount, deadline, true ); // Mint dDai using the received Dai. totalDDaiMinted = _DDAI.mint(totalDaiBought); } function tradeEtherForTokenUsingReserves( address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalEtherSold) { // Trade Ether for token using reserves. totalEtherSold = _tradeEtherForToken( token, etherAmountFromReserves, quotedTokenAmount, deadline, true ); } function tradeDaiForTokenUsingReserves( address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { // Redeem dDai if the current Dai balance is less than is required. _redeemDDaiIfNecessary(daiAmountFromReserves); // Trade Dai for token using reserves. totalDaiSold = _tradeDaiForToken( token, daiAmountFromReserves, quotedTokenAmount, deadline, routeThroughEther, true ); } function tradeTokenForDaiUsingReservesAndMintDDai( ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external onlyOwnerOr(Role.RESERVE_TRADER) returns ( uint256 totalDaiBought, uint256 totalDDaiMinted ) { // Trade the token for Dai using reserves. totalDaiBought = _tradeTokenForDai( token, tokenAmountFromReserves, quotedDaiAmount, deadline, routeThroughEther, true ); // Mint dDai using the received Dai. totalDDaiMinted = _DDAI.mint(totalDaiBought); } /** * @notice Transfer `daiAmount` Dai to `smartWallet`, providing the initial * user signing key `initialUserSigningKey` as proof that the specified smart * wallet is indeed a Dharma Smart Wallet - this assumes that the address is * derived and deployed using the Dharma Smart Wallet Factory V1. In addition, * the specified amount must be less than the configured limit amount. Only * the owner or the designated deposit manager role may call this function. * @param smartWallet address The smart wallet to transfer Dai to. * @param initialUserSigningKey address The initial user signing key supplied * when deriving the smart wallet address - this could be an EOA or a Dharma * key ring address. * @param daiAmount uint256 The amount of Dai to transfer - this must be less * than the current limit. */ function finalizeDaiDeposit( address smartWallet, address initialUserSigningKey, uint256 daiAmount ) external onlyOwnerOr(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ensureSmartWallet(smartWallet, initialUserSigningKey); // Ensure that the amount to transfer is lower than the limit. require(daiAmount < _daiLimit, "Transfer size exceeds the limit."); // Transfer the Dai to the specified smart wallet. _transferToken(_DAI, smartWallet, daiAmount); } /** * @notice Transfer `dDaiAmount` Dharma Dai to `smartWallet`, providing the * initial user signing key `initialUserSigningKey` as proof that the * specified smart wallet is indeed a Dharma Smart Wallet - this assumes that * the address is derived and deployed using the Dharma Smart Wallet Factory * V1. In addition, the Dai equivalent value of the specified dDai amount must * be less than the configured limit amount. Only the owner or the designated * deposit manager role may call this function. * @param smartWallet address The smart wallet to transfer Dai to. * @param initialUserSigningKey address The initial user signing key supplied * when deriving the smart wallet address - this could be an EOA or a Dharma * key ring address. * @param dDaiAmount uint256 The amount of Dharma Dai to transfer - the Dai * equivalent amount must be less than the current limit. */ function finalizeDharmaDaiDeposit( address smartWallet, address initialUserSigningKey, uint256 dDaiAmount ) external onlyOwnerOr(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ensureSmartWallet(smartWallet, initialUserSigningKey); // Get the current dDai exchange rate. uint256 exchangeRate = _DDAI.exchangeRateCurrent(); // Ensure that an exchange rate was actually returned. require(exchangeRate != 0, "Could not retrieve dDai exchange rate."); // Get the equivalent Dai amount of the transfer. uint256 daiEquivalent = (dDaiAmount.mul(exchangeRate)) / 1e18; // Ensure that the amount to transfer is lower than the limit. require(daiEquivalent < _daiLimit, "Transfer size exceeds the limit."); // Transfer the dDai to the specified smart wallet. _transferToken(ERC20Interface(address(_DDAI)), smartWallet, dDaiAmount); } /** * @notice Transfer `etherAmount` Ether to `smartWallet`, providing the * initial user signing key `initialUserSigningKey` as proof that the * specified smart wallet is indeed a Dharma Smart Wallet - this assumes that * the address is derived and deployed using the Dharma Smart Wallet Factory * V1. In addition, the Ether amount must be less than the configured limit * amount. Only the owner or the designated deposit manager role may call this * function. * @param smartWallet address The smart wallet to transfer Ether to. * @param initialUserSigningKey address The initial user signing key supplied * when deriving the smart wallet address - this could be an EOA or a Dharma * key ring address. * @param etherAmount uint256 The amount of Ether to transfer - this amount must be * less than the current limit. */ function finalizeEtherDeposit( address payable smartWallet, address initialUserSigningKey, uint256 etherAmount ) external onlyOwnerOr(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ensureSmartWallet(smartWallet, initialUserSigningKey); // Ensure that the amount to transfer is lower than the limit. require(etherAmount < _etherLimit, "Transfer size exceeds the limit."); // Transfer the Ether to the specified smart wallet. _transferEther(smartWallet, etherAmount); } /** * @notice Use `daiAmount` Dai mint Dharma Dai. Only the owner or the * designated adjuster role may call this function. * @param daiAmount uint256 The amount of Dai to supply when minting Dharma * Dai. * @return The amount of Dharma Dai minted. */ function mint( uint256 daiAmount ) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiMinted) { // Use the specified amount of Dai to mint dDai. dDaiMinted = _DDAI.mint(daiAmount); } /** * @notice Redeem `dDaiAmount` Dharma Dai for Dai. Only the owner or the * designated adjuster role may call this function. * @param dDaiAmount uint256 The amount of Dharma Dai to supply when redeeming * for Dai. * @return The amount of Dai received. */ function redeem( uint256 dDaiAmount ) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 daiReceived) { // Redeem the specified amount of dDai for Dai. daiReceived = _DDAI.redeem(dDaiAmount); } /** * @notice trade `usdcAmount` USDC for Dharma Dai. Only the owner or the designated * adjuster role may call this function. * @param usdcAmount uint256 The amount of USDC to supply when trading for Dharma Dai. * @param quotedDaiEquivalentAmount uint256 The expected DAI equivalent value of the * received dDai - this value is returned from the `getAndExpectedDai` view function * on the trade helper. * @return The amount of dDai received. */ function tradeUSDCForDDai( uint256 usdcAmount, uint256 quotedDaiEquivalentAmount ) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiMinted) { dDaiMinted = _TRADE_HELPER.tradeUSDCForDDai( usdcAmount, quotedDaiEquivalentAmount ); } /** * @notice tradeDDaiForUSDC `daiEquivalentAmount` Dai amount to trade in Dharma Dai * for USDC. Only the owner or the designated adjuster role may call this function. * @param daiEquivalentAmount uint256 The Dai equivalent amount to supply in Dharma * Dai when trading for USDC. * @param quotedUSDCAmount uint256 The expected USDC received in exchange for * dDai - this value is returned from the `getExpectedUSDC` view function on the * trade helper. * @return The amount of USDC received. */ function tradeDDaiForUSDC( uint256 daiEquivalentAmount, uint256 quotedUSDCAmount ) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 usdcReceived) { usdcReceived = _TRADE_HELPER.tradeDDaiForUSDC( daiEquivalentAmount, quotedUSDCAmount ); } function refillGasReserve(uint256 etherAmount) external onlyOwnerOr(Role.GAS_RESERVE_REFILLER) { // Transfer the Ether to the gas reserve. _transferEther(_GAS_RESERVE, etherAmount); emit GasReserveRefilled(etherAmount); } /** * @notice Transfer `usdcAmount` USDC for to the current primary recipient set by the * owner. Only the owner or the designated withdrawal manager role may call this function. * @param usdcAmount uint256 The amount of USDC to transfer to the primary recipient. */ function withdrawUSDCToPrimaryRecipient( uint256 usdcAmount ) external onlyOwnerOr(Role.WITHDRAWAL_MANAGER) { // Get the current primary recipient. address primaryRecipient = _primaryUSDCRecipient; require( primaryRecipient != address(0), "No USDC primary recipient currently set." ); // Transfer the supplied USDC amount to the primary recipient. _transferToken(_USDC, primaryRecipient, usdcAmount); } /** * @notice Transfer `daiAmount` Dai for to the current primary recipient set by the * owner. Only the owner or the designated withdrawal manager role may call this function. * @param daiAmount uint256 The amount of Dai to transfer to the primary recipient. */ function withdrawDaiToPrimaryRecipient( uint256 daiAmount ) external onlyOwnerOr(Role.WITHDRAWAL_MANAGER) { // Get the current primary recipient. address primaryRecipient = _primaryDaiRecipient; require( primaryRecipient != address(0), "No Dai primary recipient currently set." ); // Transfer the supplied Dai amount to the primary recipient. _transferToken(_DAI, primaryRecipient, daiAmount); } /** * @notice Transfer `usdcAmount` USDC to `recipient`. Only the owner may call * this function. * @param recipient address The account to transfer USDC to. * @param usdcAmount uint256 The amount of USDC to transfer. */ function withdrawUSDC( address recipient, uint256 usdcAmount ) external onlyOwner { // Transfer the USDC to the specified recipient. _transferToken(_USDC, recipient, usdcAmount); } /** * @notice Transfer `daiAmount` Dai to `recipient`. Only the owner may call * this function. * @param recipient address The account to transfer Dai to. * @param daiAmount uint256 The amount of Dai to transfer. */ function withdrawDai( address recipient, uint256 daiAmount ) external onlyOwner { // Transfer the Dai to the specified recipient. _transferToken(_DAI, recipient, daiAmount); } /** * @notice Transfer `dDaiAmount` Dharma Dai to `recipient`. Only the owner may * call this function. * @param recipient address The account to transfer Dharma Dai to. * @param dDaiAmount uint256 The amount of Dharma Dai to transfer. */ function withdrawDharmaDai( address recipient, uint256 dDaiAmount ) external onlyOwner { // Transfer the dDai to the specified recipient. _transferToken(ERC20Interface(address(_DDAI)), recipient, dDaiAmount); } /** * @notice Transfer `etherAmount` Ether to `recipient`. Only the owner may * call this function. * @param recipient address The account to transfer Ether to. * @param etherAmount uint256 The amount of Ether to transfer. */ function withdrawEther( address payable recipient, uint256 etherAmount ) external onlyOwner { // Transfer the Ether to the specified recipient. _transferEther(recipient, etherAmount); } /** * @notice Transfer `amount` of ERC20 token `token` to `recipient`. Only the * owner may call this function. * @param token ERC20Interface The ERC20 token to transfer. * @param recipient address The account to transfer the tokens to. * @param amount uint256 The amount of tokens to transfer. * @return A boolean to indicate if the transfer was successful - note that * unsuccessful ERC20 transfers will usually revert. */ function withdraw( ERC20Interface token, address recipient, uint256 amount ) external onlyOwner returns (bool success) { // Transfer the token to the specified recipient. success = token.transfer(recipient, amount); } /** * @notice Call account `target`, supplying value `amount` and data `data`. * Only the owner may call this function. * @param target address The account to call. * @param amount uint256 The amount of ether to include as an endowment. * @param data bytes The data to include along with the call. * @return A boolean to indicate if the call was successful, as well as the * returned data or revert reason. */ function callAny( address payable target, uint256 amount, bytes calldata data ) external onlyOwner returns (bool ok, bytes memory returnData) { // Call the specified target and supply the specified data. (ok, returnData) = target.call.value(amount)(data); } /** * @notice Set `daiAmount` as the new limit on the size of finalized deposits. * Only the owner may call this function. * @param daiAmount uint256 The new limit on the size of finalized deposits. */ function setDaiLimit(uint256 daiAmount) external onlyOwner { // Set the new limit. _daiLimit = daiAmount; } /** * @notice Set `etherAmount` as the new limit on the size of finalized deposits. * Only the owner may call this function. * @param etherAmount uint256 The new limit on the size of finalized deposits. */ function setEtherLimit(uint256 etherAmount) external onlyOwner { // Set the new limit. _etherLimit = etherAmount; } /** * @notice Set `recipient` as the new primary recipient for USDC withdrawals. * Only the owner may call this function. * @param recipient address The new primary recipient. */ function setPrimaryUSDCRecipient(address recipient) external onlyOwner { // Set the new primary recipient. _primaryUSDCRecipient = recipient; } /** * @notice Set `recipient` as the new primary recipient for Dai withdrawals. * Only the owner may call this function. * @param recipient address The new primary recipient. */ function setPrimaryDaiRecipient(address recipient) external onlyOwner { // Set the new primary recipient. _primaryDaiRecipient = recipient; } /** * @notice Pause a currently unpaused role and emit a `RolePaused` event. Only * the owner or the designated pauser may call this function. Also, bear in * mind that only the owner may unpause a role once paused. * @param role The role to pause. */ function pause(Role role) external onlyOwnerOr(Role.PAUSER) { RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(!storedRoleStatus.paused, "Role in question is already paused."); storedRoleStatus.paused = true; emit RolePaused(role); } /** * @notice Unpause a currently paused role and emit a `RoleUnpaused` event. * Only the owner may call this function. * @param role The role to pause. */ function unpause(Role role) external onlyOwner { RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(storedRoleStatus.paused, "Role in question is already unpaused."); storedRoleStatus.paused = false; emit RoleUnpaused(role); } /** * @notice Set a new account on a given role and emit a `RoleModified` event * if the role holder has changed. Only the owner may call this function. * @param role The role that the account will be set for. * @param account The account to set as the designated role bearer. */ function setRole(Role role, address account) external onlyOwner { require(account != address(0), "Must supply an account."); _setRole(role, account); } /** * @notice Remove any current role bearer for a given role and emit a * `RoleModified` event if a role holder was previously set. Only the owner * may call this function. * @param role The role that the account will be removed from. */ function removeRole(Role role) external onlyOwner { _setRole(role, address(0)); } /** * @notice External view function to check whether or not the functionality * associated with a given role is currently paused or not. The owner or the * pauser may pause any given role (including the pauser itself), but only the * owner may unpause functionality. Additionally, the owner may call paused * functions directly. * @param role The role to check the pause status on. * @return A boolean to indicate if the functionality associated with the role * in question is currently paused. */ function isPaused(Role role) external view returns (bool paused) { paused = _isPaused(role); } /** * @notice External view function to check whether the caller is the current * role holder. * @param role The role to check for. * @return A boolean indicating if the caller has the specified role. */ function isRole(Role role) external view returns (bool hasRole) { hasRole = _isRole(role); } /** * @notice External view function to check whether a "proof" that a given * smart wallet is actually a Dharma Smart Wallet, based on the initial user * signing key, is valid or not. This proof only works when the Dharma Smart * Wallet in question is derived using V1 of the Dharma Smart Wallet Factory. * @param smartWallet address The smart wallet to check. * @param initialUserSigningKey address The initial user signing key supplied * when deriving the smart wallet address - this could be an EOA or a Dharma * key ring address. * @return A boolean indicating if the specified smart wallet account is * indeed a smart wallet based on the specified initial user signing key. */ function isDharmaSmartWallet( address smartWallet, address initialUserSigningKey ) external view returns (bool dharmaSmartWallet) { dharmaSmartWallet = _isSmartWallet(smartWallet, initialUserSigningKey); } /** * @notice External view function to check the account currently holding the * deposit manager role. The deposit manager can process standard deposit * finalization via `finalizeDaiDeposit` and `finalizeDharmaDaiDeposit`, but * must prove that the recipient is a Dharma Smart Wallet and adhere to the * current deposit size limit. * @return The address of the current deposit manager, or the null address if * none is set. */ function getDepositManager() external view returns (address depositManager) { depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account; } /** * @notice External view function to check the account currently holding the * adjuster role. The adjuster can exchange Dai in reserves for Dharma Dai and * vice-versa via minting or redeeming. * @return The address of the current adjuster, or the null address if none is * set. */ function getAdjuster() external view returns (address adjuster) { adjuster = _roles[uint256(Role.ADJUSTER)].account; } /** * @notice External view function to check the account currently holding the * reserve trader role. The reserve trader can trigger trades that utilize * reserves in addition to supplied funds, if any. * @return The address of the current reserve trader, or the null address if * none is set. */ function getReserveTrader() external view returns (address reserveTrader) { reserveTrader = _roles[uint256(Role.RESERVE_TRADER)].account; } /** * @notice External view function to check the account currently holding the * withdrawal manager role. The withdrawal manager can transfer USDC to the * "primary recipient" address set by the owner. * @return The address of the current withdrawal manager, or the null address * if none is set. */ function getWithdrawalManager() external view returns (address withdrawalManager) { withdrawalManager = _roles[uint256(Role.WITHDRAWAL_MANAGER)].account; } /** * @notice External view function to check the account currently holding the * pauser role. The pauser can pause any role from taking its standard action, * though the owner will still be able to call the associated function in the * interim and is the only entity able to unpause the given role once paused. * @return The address of the current pauser, or the null address if none is * set. */ function getPauser() external view returns (address pauser) { pauser = _roles[uint256(Role.PAUSER)].account; } function getGasReserveRefiller() external view returns (address gasReserveRefiller) { gasReserveRefiller = _roles[uint256(Role.GAS_RESERVE_REFILLER)].account; } /** * @notice External view function to check the current reserves held by this * contract. * @return The Dai and Dharma Dai reserves held by this contract, as well as * the Dai-equivalent value of the Dharma Dai reserves. */ function getReserves() external view returns ( uint256 dai, uint256 dDai, uint256 dDaiUnderlying ) { dai = _DAI.balanceOf(address(this)); dDai = _DDAI.balanceOf(address(this)); dDaiUnderlying = _DDAI.balanceOfUnderlying(address(this)); } /** * @notice External view function to check the current limit on deposit amount * enforced for the deposit manager when finalizing deposits, expressed in Dai * and in Dharma Dai. * @return The Dai and Dharma Dai limit on deposit finalization amount. */ function getDaiLimit() external view returns ( uint256 daiAmount, uint256 dDaiAmount ) { daiAmount = _daiLimit; dDaiAmount = (daiAmount.mul(1e18)).div(_DDAI.exchangeRateCurrent()); } /** * @notice External view function to check the current limit on deposit amount * enforced for the deposit manager when finalizing Ether deposits. * @return The Ether limit on deposit finalization amount. */ function getEtherLimit() external view returns (uint256 etherAmount) { etherAmount = _etherLimit; } /** * @notice External view function to check the address of the current * primary recipient for USDC. * @return The primary recipient for USDC. */ function getPrimaryUSDCRecipient() external view returns ( address recipient ) { recipient = _primaryUSDCRecipient; } /** * @notice External view function to check the address of the current * primary recipient for Dai. * @return The primary recipient for Dai. */ function getPrimaryDaiRecipient() external view returns ( address recipient ) { recipient = _primaryDaiRecipient; } /** * @notice External view function to check the current implementation * of this contract (i.e. the "logic" for the contract). * @return The current implementation for this contract. */ function getImplementation() external view returns ( address implementation ) { (bool ok, bytes memory returnData) = address( 0x481B1a16E6675D33f8BBb3a6A58F5a9678649718 ).staticcall(""); require(ok && returnData.length == 32, "Invalid implementation."); implementation = abi.decode(returnData, (address)); } /** * @notice External pure function to get the address of the actual * contract instance (i.e. the "storage" foor this contract). * @return The address of this contract instance. */ function getInstance() external pure returns (address instance) { instance = address(0x09cd826D4ABA4088E1381A1957962C946520952d); } function getVersion() external view returns (uint256 version) { version = _VERSION; } function _grantUniswapRouterApprovalIfNecessary(ERC20Interface token, uint256 amount) internal { if (token.allowance(address(this), address(_UNISWAP_ROUTER)) < amount) { // Try removing approval for Uniswap router first as a workaround for unusual tokens. (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector( token.approve.selector, address(_UNISWAP_ROUTER), uint256(0) ) ); // Grant approval for Uniswap router to transfer tokens on behalf of this contract. (success, data) = address(token).call( abi.encodeWithSelector( token.approve.selector, address(_UNISWAP_ROUTER), uint256(-1) ) ); if (!success) { // Some really janky tokens only allow setting approval up to current balance. (success, data) = address(token).call( abi.encodeWithSelector( token.approve.selector, address(_UNISWAP_ROUTER), amount ) ); } require( success && (data.length == 0 || abi.decode(data, (bool))), "Token approval for Uniswap router failed." ); } } function _tradeEtherForDai( uint256 etherAmount, uint256 quotedDaiAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalDaiBought) { // Establish path from Ether to Dai. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( _WETH, address(_DAI), false ); // Trade Ether for Dai on Uniswap (send to this contract). amounts = _UNISWAP_ROUTER.swapExactETHForTokens.value(etherAmount)( quotedDaiAmount, path, address(this), deadline ); totalDaiBought = amounts[1]; _fireTradeEvent( fromReserves, TradeType.ETH_TO_DAI, address(0), etherAmount, quotedDaiAmount, totalDaiBought.sub(quotedDaiAmount) ); } function _tradeDaiForEther( uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalDaiSold) { // Establish path from Dai to Ether. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(_DAI), _WETH, false ); // Trade Dai for quoted Ether amount on Uniswap (send to appropriate recipient). amounts = _UNISWAP_ROUTER.swapTokensForExactETH( quotedEtherAmount, daiAmount, path, fromReserves ? address(this) : msg.sender, deadline ); totalDaiSold = amounts[0]; _fireTradeEvent( fromReserves, TradeType.DAI_TO_ETH, address(0), daiAmount, quotedEtherAmount, daiAmount.sub(totalDaiSold) ); } /** * @notice Internal trade function. If token is _TRADE_FOR_USDC_AND_RETAIN_FLAG, * trade for USDC and retain the full output amount by replacing the recipient * ("to" input) on the swapETHForExactTokens call. */ function _tradeEtherForToken( address tokenReceivedOrUSDCFlag, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalEtherSold) { // Set swap target token address tokenReceived = tokenReceivedOrUSDCFlag == _TRADE_FOR_USDC_AND_RETAIN_FLAG ? address(_USDC) : tokenReceivedOrUSDCFlag; // Establish path from Ether to token. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( _WETH, tokenReceived, false ); // Trade Ether for quoted token amount on Uniswap and send to appropriate recipient. amounts = _UNISWAP_ROUTER.swapETHForExactTokens.value(etherAmount)( quotedTokenAmount, path, fromReserves || tokenReceivedOrUSDCFlag == _TRADE_FOR_USDC_AND_RETAIN_FLAG ? address(this) : msg.sender, deadline ); totalEtherSold = amounts[0]; _fireTradeEvent( fromReserves, TradeType.ETH_TO_TOKEN, tokenReceivedOrUSDCFlag, etherAmount, quotedTokenAmount, etherAmount.sub(totalEtherSold) ); } function _tradeTokenForEther( ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalEtherBought) { // Approve Uniswap router to transfer tokens on behalf of this contract. _grantUniswapRouterApprovalIfNecessary(token, tokenAmount); // Establish path from target token to Ether. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(token), _WETH, false ); // Trade tokens for quoted Ether amount on Uniswap (send to this contract). amounts = _UNISWAP_ROUTER.swapExactTokensForETH( tokenAmount, quotedEtherAmount, path, address(this), deadline ); totalEtherBought = amounts[1]; _fireTradeEvent( fromReserves, TradeType.TOKEN_TO_ETH, address(token), tokenAmount, quotedEtherAmount, totalEtherBought.sub(quotedEtherAmount) ); } function _tradeDaiForToken( address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther, bool fromReserves ) internal returns (uint256 totalDaiSold) { // Establish path (direct or routed through Ether) from Dai to target token. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(_DAI), address(token), routeThroughEther ); // Trade the Dai for the quoted token amount on Uniswap and send to appropriate recipient. amounts = _UNISWAP_ROUTER.swapTokensForExactTokens( quotedTokenAmount, daiAmount, path, fromReserves ? address(this) : msg.sender, deadline ); totalDaiSold = amounts[0]; _fireTradeEvent( fromReserves, TradeType.DAI_TO_TOKEN, address(token), daiAmount, quotedTokenAmount, daiAmount.sub(totalDaiSold) ); } function _tradeTokenForDai( ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther, bool fromReserves ) internal returns (uint256 totalDaiBought) { // Approve Uniswap router to transfer tokens on behalf of this contract. _grantUniswapRouterApprovalIfNecessary(token, tokenAmount); // Establish path (direct or routed through Ether) from target token to Dai. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(token), address(_DAI), routeThroughEther ); // Trade the Dai for the quoted token amount on Uniswap (send to this contract). amounts = _UNISWAP_ROUTER.swapExactTokensForTokens( tokenAmount, quotedDaiAmount, path, address(this), deadline ); totalDaiBought = amounts[path.length - 1]; _fireTradeEvent( fromReserves, TradeType.TOKEN_TO_DAI, address(token), tokenAmount, quotedDaiAmount, totalDaiBought.sub(quotedDaiAmount) ); } /** * @notice Internal trade function. If tokenReceived is _TRADE_FOR_USDC_AND_RETAIN_FLAG, * trade for USDC and retain the full output amount by replacing the recipient * ("to" input) on the swapTokensForExactTokens call. */ function _tradeTokenForToken( address account, ERC20Interface tokenProvided, address tokenReceivedOrUSDCFlag, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) internal returns (uint256 totalTokensSold) { uint256 retainedAmount; address tokenRecieved; address recipient; // Approve Uniswap router to transfer tokens on behalf of this contract. _grantUniswapRouterApprovalIfNecessary(tokenProvided, tokenProvidedAmount); // Set recipient, swap target token if (tokenReceivedOrUSDCFlag == _TRADE_FOR_USDC_AND_RETAIN_FLAG) { recipient = address(this); tokenRecieved = address(_USDC); } else { recipient = account; tokenRecieved = tokenReceivedOrUSDCFlag; } if (routeThroughEther == false) { // Establish direct path between tokens. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(tokenProvided), tokenRecieved, false ); // Trade for the quoted token amount on Uniswap and send to recipient. amounts = _UNISWAP_ROUTER.swapTokensForExactTokens( quotedTokenReceivedAmount, tokenProvidedAmount, path, recipient, deadline ); totalTokensSold = amounts[0]; retainedAmount = tokenProvidedAmount.sub(totalTokensSold); } else { // Establish path between provided token and WETH. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(tokenProvided), _WETH, false ); // Trade all provided tokens for WETH on Uniswap and send to this contract. amounts = _UNISWAP_ROUTER.swapExactTokensForTokens( tokenProvidedAmount, 0, path, address(this), deadline ); retainedAmount = amounts[1]; // Establish path between WETH and received token. (path, amounts) = _createPathAndAmounts( _WETH, tokenRecieved, false ); // Trade bought WETH for received token on Uniswap and send to recipient. amounts = _UNISWAP_ROUTER.swapTokensForExactTokens( quotedTokenReceivedAmount, retainedAmount, path, recipient, deadline ); totalTokensSold = amounts[0]; retainedAmount = retainedAmount.sub(totalTokensSold); } emit Trade( account, address(tokenProvided), tokenReceivedOrUSDCFlag, routeThroughEther ? _WETH : address(tokenProvided), tokenProvidedAmount, quotedTokenReceivedAmount, retainedAmount ); } /** * @notice Internal function to set a new account on a given role and emit a * `RoleModified` event if the role holder has changed. * @param role The role that the account will be set for. Permitted roles are * deposit manager (0), adjuster (1), and pauser (2). * @param account The account to set as the designated role bearer. */ function _setRole(Role role, address account) internal { RoleStatus storage storedRoleStatus = _roles[uint256(role)]; if (account != storedRoleStatus.account) { storedRoleStatus.account = account; emit RoleModified(role, account); } } function _fireTradeEvent( bool fromReserves, TradeType tradeType, address token, uint256 suppliedAmount, uint256 receivedAmount, uint256 retainedAmount ) internal { uint256 t = uint256(tradeType); emit Trade( fromReserves ? address(this) : msg.sender, t < 2 ? address(_DAI) : (t % 2 == 0 ? address(0) : token), (t > 1 && t < 4) ? address(_DAI) : (t % 2 == 0 ? token : address(0)), t < 4 ? address(_DAI) : address(0), suppliedAmount, receivedAmount, retainedAmount ); } /** * @notice Internal view function to check whether the caller is the current * role holder. * @param role The role to check for. * @return A boolean indicating if the caller has the specified role. */ function _isRole(Role role) internal view returns (bool hasRole) { hasRole = msg.sender == _roles[uint256(role)].account; } /** * @notice Internal view function to check whether the given role is paused or * not. * @param role The role to check for. * @return A boolean indicating if the specified role is paused or not. */ function _isPaused(Role role) internal view returns (bool paused) { paused = _roles[uint256(role)].paused; } /** * @notice Internal view function to enforce that the given initial user signing * key resolves to the given smart wallet when deployed through the Dharma Smart * Wallet Factory V1. (staging version) * @param smartWallet address The smart wallet. * @param initialUserSigningKey address The initial user signing key. */ function _isSmartWallet( address smartWallet, address initialUserSigningKey ) internal pure returns (bool) { // Derive the keccak256 hash of the smart wallet initialization code. bytes32 initCodeHash = keccak256( abi.encodePacked( _WALLET_CREATION_CODE_HEADER, initialUserSigningKey, _WALLET_CREATION_CODE_FOOTER ) ); // Attempt to derive a smart wallet address that matches the one provided. address target; for (uint256 nonce = 0; nonce < 10; nonce++) { target = address( // derive the target deployment address. uint160( // downcast to match the address type. uint256( // cast to uint to truncate upper digits. keccak256( // compute CREATE2 hash using all inputs. abi.encodePacked( // pack all inputs to the hash together. _CREATE2_HEADER, // pass in control character + factory address. nonce, // pass in current nonce as the salt. initCodeHash // pass in hash of contract creation code. ) ) ) ) ); // Exit early if the provided smart wallet matches derived target address. if (target == smartWallet) { return true; } // Otherwise, increment the nonce and derive a new salt. nonce++; } // Explicity recognize no target was found matching provided smart wallet. return false; } function _redeemDDaiIfNecessary(uint256 daiAmountFromReserves) internal { uint256 daiBalance = _DAI.balanceOf(address(this)); if (daiBalance < daiAmountFromReserves) { uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance; _DDAI.redeemUnderlying(additionalDaiRequired); } } function _transferToken(ERC20Interface token, address to, uint256 amount) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(token.transfer.selector, to, amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Transfer out failed.' ); } function _transferEther(address recipient, uint256 etherAmount) internal { // Send quoted Ether amount to recipient and revert with reason on failure. (bool ok, ) = recipient.call.value(etherAmount)(""); if (!ok) { assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } } function _transferInToken(ERC20Interface token, address from, uint256 amount) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(token.transferFrom.selector, from, address(this), amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Transfer in failed.' ); } function _ensureSmartWallet( address smartWallet, address initialUserSigningKey ) internal pure { require( _isSmartWallet(smartWallet, initialUserSigningKey), "Could not resolve smart wallet using provided signing key." ); } function _createPathAndAmounts( address start, address end, bool routeThroughEther ) internal pure returns (address[] memory, uint256[] memory) { uint256 pathLength = routeThroughEther ? 3 : 2; address[] memory path = new address[](pathLength); path[0] = start; if (routeThroughEther) { path[1] = _WETH; } path[pathLength - 1] = end; return (path, new uint256[](pathLength)); } /** * @notice Modifier that throws if called by any account other than the owner * or the supplied role, or if the caller is not the owner and the role in * question is paused. * @param role The role to require unless the caller is the owner. */ modifier onlyOwnerOr(Role role) { if (!isOwner()) { require(_isRole(role), "Caller does not have a required role."); require(!_isPaused(role), "Role in question is currently paused."); } _; } }
Redeem dDai if the current Dai balance is less than is required. Trade Dai for token using reserves.
function tradeDaiForTokenUsingReserves( address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { _redeemDDaiIfNecessary(daiAmountFromReserves); totalDaiSold = _tradeDaiForToken( token, daiAmountFromReserves, quotedTokenAmount, deadline, routeThroughEther, true ); }
606,945
pragma solidity ^0.5.11; interface ERC20 { function totalSupply() external view returns (uint supply); function balanceOf(address _owner) external view returns (uint balance); function transfer(address _to, uint _value) external returns (bool success); function transferFrom(address _from, address _to, uint _value) external returns (bool success); function approve(address _spender, uint _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } interface KyberReserveIf { function getConversionRate(ERC20 src, ERC20 dest, uint srcQty, uint blockNumber) external view returns(uint); } contract KyberNetworkIf { mapping(address=>address[]) public reservesPerTokenSrc; //reserves supporting token to eth mapping(address=>address[]) public reservesPerTokenDest;//reserves support eth to token } contract CheckReserveSplit { ERC20 constant ETH = ERC20(address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)); KyberNetworkIf constant kyber = KyberNetworkIf(0x9ae49C0d7F8F9EF4B864e004FE86Ac8294E20950); ERC20 constant dai = ERC20(0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359); ERC20 constant usdc = ERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); uint public numSplitRateIteration = 11; mapping(address=>address[]) reservesPerTokenDest;//reserves supporting eth to token constructor () public { } function setNumSplitRateCalls (uint num) public { numSplitRateIteration = num; } function copyReserves(ERC20 token) public { KyberReserveIf reserve; uint index; while(true) { reserve = KyberReserveIf(getReserveTokenDest(address(token), index)); if (reserve == KyberReserveIf(address(0x0))) break; reservesPerTokenDest[address(token)].push(address(reserve)); index++; } } function getres1ReservesEthToToken(ERC20 token, uint tradeSizeEth) internal view returns(KyberReserveIf res1, KyberReserveIf res2, uint res1Rate, uint res2Rate, uint index) { KyberReserveIf reserve; uint rate; index = 0; uint querySizeEth; if (tradeSizeEth < 50) { querySizeEth = tradeSizeEth; } else { querySizeEth = tradeSizeEth * 55 / 100; } // fetch resereves find reserve with res1 rate and with 2nd res1. for(index = 0; index < reservesPerTokenDest[address(token)].length; index++) { reserve = KyberReserveIf(reservesPerTokenDest[address(token)][index]); if (reserve == KyberReserveIf(address(0x0))) continue; rate = reserve.getConversionRate(ETH, token, querySizeEth * 10 ** 18, block.number); if(rate > res1Rate) { if (res1Rate > res2Rate) { res2Rate = res1Rate; res2 = res1; } res1Rate = rate; res1 = reserve; } else if (rate > res2Rate) { res2Rate = rate; res2 = reserve; } } res2Rate = res2.getConversionRate(ETH, token, (tradeSizeEth - querySizeEth) * 10 ** 18, block.number); } function getReserveTokenDest (address token, uint index) internal view returns (address reserve) { (bool success, bytes memory returnData) = address(kyber).staticcall( abi.encodePacked( // This encodes the function to call and the parameters to pass to that function kyber.reservesPerTokenDest.selector, abi.encode(token, index) ) ); if (success) { reserve = abi.decode(returnData, (address)); } else { // transferFrom reverted. However, the complete tx did not revert and we can handle the case here. reserve = address(0x0); } } function getres1EthToDaiReserves100Eth() public view returns(KyberReserveIf res1, KyberReserveIf res2, uint res1Rate, uint res2Rate, uint index) { return getres1ReservesEthToToken(dai, 100); } function getres1EthToUsdcReserves100Eth() public view returns(KyberReserveIf res1, KyberReserveIf res2, uint res1Rate, uint res2Rate, uint index) { return getres1ReservesEthToToken(usdc, 100); } function getSplitValueEthToToken(ERC20 token, uint tradeSizeEth) internal view returns(uint splitValueEth, KyberReserveIf res1, KyberReserveIf res2) { uint numSplitCalls = numSplitRateIteration; (res1, res2, , , ) = getres1ReservesEthToToken(token, tradeSizeEth); // set step size at trade size / 4 uint stepSizeWei = (tradeSizeEth * 10 ** 18) / 4; // set first split value to trade size / 2 uint splitValueWei = (tradeSizeEth * 10 ** 18) / 2; (uint lastSplitRate, , ) = calcCombinedRate(token, res1, res2, splitValueWei, (tradeSizeEth * 10 ** 18)); uint newSplitRate; while (numSplitCalls-- > 0) { (newSplitRate, , ) = calcCombinedRate(token, res1, res2, (splitValueWei + stepSizeWei), (tradeSizeEth * 10 ** 18)); if (newSplitRate > lastSplitRate) { lastSplitRate = newSplitRate; splitValueWei += stepSizeWei; } stepSizeWei /= 2; } splitValueEth = splitValueWei / 10 ** 18; } function compareSplitTrade(ERC20 token, uint tradeValueEth) internal view returns(uint rateReserve1, uint rateReserve1and2, uint amountReserve1, uint amountRes1and2, uint splitValueEth, KyberReserveIf res1, KyberReserveIf res2, uint rate1OnSplit, uint rate2OnSplit) { (splitValueEth, res1, res2) = getSplitValueEthToToken(token, tradeValueEth); rateReserve1 = res1.getConversionRate(ETH, token, tradeValueEth * 10 ** 18, block.number); (rateReserve1and2, rate1OnSplit, rate2OnSplit) = calcCombinedRate(token, res1, res2, splitValueEth * 10 ** 18, tradeValueEth * 10 ** 18); amountReserve1 = rateReserve1 * tradeValueEth / 10 ** 18; amountRes1and2 = rateReserve1and2 * tradeValueEth / 10 ** 18; } function getDaiSplitTradeGas() public returns(uint rateReserve1, uint rateReserve1and2, uint amountReserve1, uint amountRes1and2, uint splitValueEth, KyberReserveIf res1, KyberReserveIf res2, uint rate1OnSplit, uint rate2OnSplit) { return viewSplitTradeEthToDai(120); } function viewSplitTradeEthToDai(uint tradeValueEth) public view returns(uint rateReserve1, uint rateReserve1and2, uint amountReserve1, uint amountRes1and2, uint splitValueEth, KyberReserveIf res1, KyberReserveIf res2, uint rate1OnSplit, uint rate2OnSplit) { return compareSplitTrade(dai, tradeValueEth); } function viewSplitTradeEthToUsdc(uint tradeValueEth) public view returns(uint rateReserve1, uint rateReserve1and2, uint amountReserve1, uint amountRes1and2, uint splitValueEth, KyberReserveIf res1, KyberReserveIf res2, uint rate1OnSplit, uint rate2OnSplit) { return compareSplitTrade(usdc, tradeValueEth); } function calcCombinedRate(ERC20 token, KyberReserveIf res1, KyberReserveIf res2, uint splitValueWei, uint tradeValueWei) internal view returns(uint combinedRate, uint rate1OnSplit, uint rate2OnSplit) { rate1OnSplit = res1.getConversionRate(ETH, token, splitValueWei, block.number); rate2OnSplit = res2.getConversionRate(ETH, token, (tradeValueWei - splitValueWei), block.number); combinedRate = (rate1OnSplit * splitValueWei + rate2OnSplit * (tradeValueWei - splitValueWei)) / tradeValueWei; } }
set step size at trade size / 4 set first split value to trade size / 2
function getSplitValueEthToToken(ERC20 token, uint tradeSizeEth) internal view returns(uint splitValueEth, KyberReserveIf res1, KyberReserveIf res2) { uint numSplitCalls = numSplitRateIteration; (res1, res2, , , ) = getres1ReservesEthToToken(token, tradeSizeEth); uint stepSizeWei = (tradeSizeEth * 10 ** 18) / 4; uint splitValueWei = (tradeSizeEth * 10 ** 18) / 2; (uint lastSplitRate, , ) = calcCombinedRate(token, res1, res2, splitValueWei, (tradeSizeEth * 10 ** 18)); uint newSplitRate; while (numSplitCalls-- > 0) { (newSplitRate, , ) = calcCombinedRate(token, res1, res2, (splitValueWei + stepSizeWei), (tradeSizeEth * 10 ** 18)); if (newSplitRate > lastSplitRate) { lastSplitRate = newSplitRate; splitValueWei += stepSizeWei; } stepSizeWei /= 2; } splitValueEth = splitValueWei / 10 ** 18; }
7,290,665
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import { OracleLibrary } from "@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol"; import { IUniswapV3Factory } from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol"; import { LowGasSafeMath } from "@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol"; interface IERC20Decimals { function decimals() external view returns (uint8); } library UniswapV3OracleHelper { using LowGasSafeMath for uint256; IUniswapV3Factory internal constant UniswapV3Factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /** * @notice This function should return the price of baseToken in quoteToken, as in: quote/base (WETH/TORN) * @dev uses the Uniswap written OracleLibrary "getQuoteAtTick", does not call external libraries, * uses decimals() for the correct power of 10 * @param baseToken token which will be denominated in quote token * @param quoteToken token in which price will be denominated * @param fee the uniswap pool fee, pools have different fees so this is a pool selector for our usecase * @param period the amount of seconds we are going to look into the past for the new token price * @return returns the price of baseToken in quoteToken * */ function getPriceOfTokenInToken( address baseToken, address quoteToken, uint24 fee, uint32 period ) internal view returns (uint256) { uint128 base = uint128(10)**uint128(IERC20Decimals(quoteToken).decimals()); if (baseToken == quoteToken) return base; else return OracleLibrary.getQuoteAtTick( OracleLibrary.consult(UniswapV3Factory.getPool(baseToken, quoteToken, fee), period), base, baseToken, quoteToken ); } /** * @notice This function should return the price of token in WETH * @dev simply feeds WETH in to the above function * @param token token which will be denominated in WETH * @param fee the uniswap pool fee, pools have different fees so this is a pool selector for our usecase * @param period the amount of seconds we are going to look into the past for the new token price * @return returns the price of token in WETH * */ function getPriceOfTokenInWETH( address token, uint24 fee, uint32 period ) internal view returns (uint256) { return getPriceOfTokenInToken(token, WETH, fee, period); } /** * @notice This function should return the price of WETH in token * @dev simply feeds WETH into getPriceOfTokenInToken * @param token token which WETH will be denominated in * @param fee the uniswap pool fee, pools have different fees so this is a pool selector for our usecase * @param period the amount of seconds we are going to look into the past for the new token price * @return returns the price of token in WETH * */ function getPriceOfWETHInToken( address token, uint24 fee, uint32 period ) internal view returns (uint256) { return getPriceOfTokenInToken(WETH, token, fee, period); } /** * @notice This function returns the price of token[1] in token[0], but more precisely and importantly the price ratio of the tokens in WETH * @dev this is done as to always have good prices due to WETH-token pools mostly always having the most liquidity * @param tokens array of tokens to get ratio for * @param fees the uniswap pool FEES, since these are two independent tokens * @param period the amount of seconds we are going to look into the past for the new token price * @return returns the price of token[1] in token[0] * */ function getPriceRatioOfTokens( address[2] memory tokens, uint24[2] memory fees, uint32 period ) internal view returns (uint256) { return getPriceOfTokenInWETH(tokens[0], fees[0], period).mul(1e18) / getPriceOfTokenInWETH(tokens[1], fees[1], period); } }
This function should return the price of WETH in token simply feeds WETH into getPriceOfTokenInToken token token which WETH will be denominated in fee the uniswap pool fee, pools have different fees so this is a pool selector for our usecase period the amount of seconds we are going to look into the past for the new token price return returns the price of token in WETH /
function getPriceOfWETHInToken( address token, uint24 fee, uint32 period ) internal view returns (uint256) { return getPriceOfTokenInToken(WETH, token, fee, period); }
2,487,551
// https://docs.erisindustries.com/tutorials/solidity/solidity-1/ // Base class for contracts that are used in a doug system. contract DougEnabled { address DOUG; function setDougAddress(address dougAddr) returns (bool result){ // Once the doug address is set, don't allow it to be set again, except by the // doug contract itself. if(DOUG != 0x0 && msg.sender != DOUG){ return false; } DOUG = dougAddr; return true; } // Makes it so that Doug is the only contract that may kill it. function remove(){ if(msg.sender == DOUG){ suicide(DOUG); } } } // The Doug contract. contract Doug { address owner; // This is where we keep all the contracts. mapping (bytes32 => address) public contracts; modifier onlyOwner { //a modifier to reduce code replication if (msg.sender == owner) // this ensures that only the owner can access the function _ } // Constructor function Doug(){ owner = msg.sender; } // Add a new contract to Doug. This will overwrite an existing contract. function addContract(bytes32 name, address addr) onlyOwner returns (bool result) { DougEnabled de = DougEnabled(addr); // Don't add the contract if this does not work. if(!de.setDougAddress(address(this))) { return false; } contracts[name] = addr; return true; } // Remove a contract from Doug. We could also suicide if we want to. function removeContract(bytes32 name) onlyOwner returns (bool result) { if (contracts[name] == 0x0){ return false; } contracts[name] = 0x0; return true; } function remove() onlyOwner { address fm = contracts["fundmanager"]; address perms = contracts["perms"]; address permsdb = contracts["permsdb"]; address bank = contracts["bank"]; address bankdb = contracts["bankdb"]; // Remove everything. if(fm != 0x0){ DougEnabled(fm).remove(); } if(perms != 0x0){ DougEnabled(perms).remove(); } if(permsdb != 0x0){ DougEnabled(permsdb).remove(); } if(bank != 0x0){ DougEnabled(bank).remove(); } if(bankdb != 0x0){ DougEnabled(bankdb).remove(); } // Finally, remove doug. Doug will now have all the funds of the other contracts, // and when suiciding it will all go to the owner. suicide(owner); } } // Interface for getting contracts from Doug contract ContractProvider { function contracts(bytes32 name) returns (address addr) {} } // Base class for contracts that only allow the fundmanager to call them. // Note that it inherits from DougEnabled contract FundManagerEnabled is DougEnabled { // Makes it easier to check that fundmanager is the caller. function isFundManager() constant returns (bool) { if(DOUG != 0x0){ address fm = ContractProvider(DOUG).contracts("fundmanager"); return msg.sender == fm; } return false; } } // Permissions database contract PermissionsDb is DougEnabled { mapping (address => uint8) public perms; // Set the permissions of an account. function setPermission(address addr, uint8 perm) returns (bool res) { if(DOUG != 0x0){ address permC = ContractProvider(DOUG).contracts("perms"); if (msg.sender == permC ){ perms[addr] = perm; return true; } return false; } else { return false; } } } // Permissions contract Permissions is FundManagerEnabled { // Set the permissions of an account. function setPermission(address addr, uint8 perm) returns (bool res) { if (!isFundManager()){ return false; } address permdb = ContractProvider(DOUG).contracts("permsdb"); if ( permdb == 0x0 ) { return false; } return PermissionsDb(permdb).setPermission(addr, perm); } } // The bank database contract BankDb is DougEnabled { mapping (address => uint) public balances; function deposit(address addr) returns (bool res) { if(DOUG != 0x0){ address bank = ContractProvider(DOUG).contracts("bank"); if (msg.sender == bank ){ balances[addr] += msg.value; return true; } } // Return if deposit cannot be made. msg.sender.send(msg.value); return false; } function withdraw(address addr, uint amount) returns (bool res) { if(DOUG != 0x0){ address bank = ContractProvider(DOUG).contracts("bank"); if (msg.sender == bank ){ uint oldBalance = balances[addr]; if(oldBalance >= amount){ msg.sender.send(amount); balances[addr] = oldBalance - amount; return true; } } } return false; } } // The bank contract Bank is FundManagerEnabled { // Attempt to withdraw the given 'amount' of Ether from the account. function deposit(address userAddr) returns (bool res) { if (!isFundManager()){ return false; } address bankdb = ContractProvider(DOUG).contracts("bankdb"); if ( bankdb == 0x0 ) { // If the user sent money, we should return it if we can't deposit. msg.sender.send(msg.value); return false; } // Use the interface to call on the bank contract. We pass msg.value along as well. bool success = BankDb(bankdb).deposit.value(msg.value)(userAddr); // If the transaction failed, return the Ether to the caller. if (!success) { msg.sender.send(msg.value); } return success; } // Attempt to withdraw the given 'amount' of Ether from the account. function withdraw(address userAddr, uint amount) returns (bool res) { if (!isFundManager()){ return false; } address bankdb = ContractProvider(DOUG).contracts("bankdb"); if ( bankdb == 0x0 ) { return false; } // Use the interface to call on the bank contract. bool success = BankDb(bankdb).withdraw(userAddr, amount); // If the transaction succeeded, pass the Ether on to the caller. if (success) { userAddr.send(amount); } return success; } } // The fund manager contract FundManager is DougEnabled { // We still want an owner. address owner; // Constructor function FundManager(){ owner = msg.sender; } // Attempt to withdraw the given 'amount' of Ether from the account. function deposit() returns (bool res) { if (msg.value == 0){ return false; } address bank = ContractProvider(DOUG).contracts("bank"); address permsdb = ContractProvider(DOUG).contracts("permsdb"); if ( bank == 0x0 || permsdb == 0x0 || PermissionsDb(permsdb).perms(msg.sender) < 1) { // If the user sent money, we should return it if we can't deposit. msg.sender.send(msg.value); return false; } // Use the interface to call on the bank contract. We pass msg.value along as well. bool success = Bank(bank).deposit.value(msg.value)(msg.sender); // If the transaction failed, return the Ether to the caller. if (!success) { msg.sender.send(msg.value); } return success; } // Attempt to withdraw the given 'amount' of Ether from the account. function withdraw(uint amount) returns (bool res) { if (amount == 0){ return false; } address bank = ContractProvider(DOUG).contracts("bank"); address permsdb = ContractProvider(DOUG).contracts("permsdb"); if ( bank == 0x0 || permsdb == 0x0 || PermissionsDb(permsdb).perms(msg.sender) < 1) { // If the user sent money, we should return it if we can't deposit. msg.sender.send(msg.value); return false; } // Use the interface to call on the bank contract. bool success = Bank(bank).withdraw(msg.sender, amount); // If the transaction succeeded, pass the Ether on to the caller. if (success) { msg.sender.send(amount); } return success; } // Set the permissions for a given address. function setPermission(address addr, uint8 permLvl) returns (bool res) { if (msg.sender != owner){ return false; } address perms = ContractProvider(DOUG).contracts("perms"); if ( perms == 0x0 ) { return false; } return Permissions(perms).setPermission(addr,permLvl); } }
Once the doug address is set, don't allow it to be set again, except by the doug contract itself.
function setDougAddress(address dougAddr) returns (bool result){ if(DOUG != 0x0 && msg.sender != DOUG){ return false; } DOUG = dougAddr; return true; }
13,105,298
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @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/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/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/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @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); } } pragma solidity ^0.8.0; contract EarHoLo is ERC721Enumerable, Ownable { using Strings for uint256; string baseURI; string baseExtension = ".json"; uint256 first_cost = 0.08 ether; uint256 second_cost = 0.13 ether; uint256 final_cost = 0.15 ether; uint256 public maxSupply = 2056; uint advancedKey = 20220216; uint256 public maxMintAmount = 10; uint public mintAmount; uint256 mintSupply = 1100; uint public advancedMintAmount = 1100; uint256 advancedMintSupply = 1500; uint public pubMintAmount = 1500; uint256 pubMintSupply = 1700; uint adminMintAmount = 1700; bool public paused = true; bool public finalPaused = true; constructor( string memory _name, string memory _symbol, string memory _initBaseURI ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) public payable { uint256 supply = mintAmount; require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= mintSupply); if (msg.sender != owner()) { require(msg.value >= first_cost * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } // change mint number mintAmount += _mintAmount; } function pub_mint(uint256 _mintAmount) public payable { uint256 supply = pubMintAmount; require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= pubMintSupply); if (msg.sender != owner()) { require(msg.value >= final_cost * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } // change mint number pubMintAmount += _mintAmount; } function advanced_mint(uint256 _mintAmount, uint key) public payable { // save gas uint256 supply = advancedMintAmount; require(key == advancedKey, "can not mint"); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= advancedMintSupply); if (msg.sender != owner()) { require(msg.value >= second_cost * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } // change mint num advancedMintAmount += _mintAmount; } function admin_mint(uint256 _mintAmount) public onlyOwner { // save gas uint256 supply = adminMintAmount; require(_mintAmount > 0); require(supply + _mintAmount <= maxSupply); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } // change mint num adminMintAmount += _mintAmount; } // public // uint mintAmount; // uint256 mintSupply = 1100; // uint advancedMintAmount = 1100; // uint256 advancedMintSupply = 1500; // uint public pubMintAmount = 1500; // uint256 pubMintSupply = 1700; function final_mint(uint256 _mintAmount) public payable { uint left = (mintSupply - mintAmount) + (advancedMintSupply - advancedMintAmount) + (pubMintSupply - pubMintAmount); require(!finalPaused); uint price; uint256 mintLeft = mintSupply - mintAmount; uint256 advancedMintLeft = advancedMintSupply - advancedMintAmount; // uint advancedNeedMint; // uint pubNeedMint; require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(_mintAmount <= left); // first mint left if(mintLeft > 0) { // need advancedLeft mint? uint advancedNeedMint = mintLeft >= _mintAmount ? 0 : _mintAmount - mintLeft; uint thisMintAmount = _mintAmount - advancedNeedMint; if (msg.sender != owner()) { price += final_cost * thisMintAmount; require(msg.value >= price, "price error"); } for (uint256 i = 1; i <= thisMintAmount; i++) { _safeMint(msg.sender, mintAmount + i); } mintAmount += thisMintAmount; if(advancedNeedMint == 0) { return; } else { _mintAmount = advancedNeedMint; } // advanced mint left } if(advancedMintLeft > 0) { // need pub mint left uint pubNeedMint = advancedMintLeft >= _mintAmount ? 0 : _mintAmount - advancedMintLeft; uint thisMintAmount = _mintAmount - pubNeedMint; if (msg.sender != owner()) { price += final_cost * thisMintAmount; require(msg.value >= price, "price error"); } for (uint256 i = 1; i <= thisMintAmount; i++) { _safeMint(msg.sender, advancedMintAmount + i); } advancedMintAmount += thisMintAmount; if(pubNeedMint == 0) { return; } else { _mintAmount = pubNeedMint; } } if (msg.sender != owner()) { price += final_cost * _mintAmount; require(msg.value >= price, "price error"); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, pubMintAmount + i); } pubMintAmount += _mintAmount; } // https://8.210.156.178/nft/json/1.json function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } function setAdvancedKey(uint _newKey) public onlyOwner { advancedKey = _newKey; } function setMaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function pause(bool _state) public onlyOwner { paused = _state; } function finalPause(bool _state) public onlyOwner { finalPaused = _state; } // uint256 first_cost = 0.08 ether; // uint256 second_cost = 0.13 ether; // uint256 final_cost = 0.15 ether; function changeFirstCost(uint _p) public onlyOwner { first_cost = _p; } function changeSecondCost(uint _p) public onlyOwner { second_cost = _p; } function changeFinalCost(uint _p) public onlyOwner { final_cost = _p; } function withdraw() public onlyOwner { (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success); } }
https:8.210.156.178/nft/json/1.json
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; }
1,416,368
// IKB TOKEN // By Mitchell F. Chan /* OVERVIEW: This contract manages the purchase and transferral of Digital Zones of Immaterial Pictorial Sensibility. It reproduces the rules originally created by Yves Klein which governed the transferral of his original Zones of Immaterial Pictorial Sensibility. The project is described in full in the Blue Paper included in this repository. */ pragma solidity ^0.4.15; // interface for ERC20 standard token contract ERC20 { function totalSupply() constant returns (uint256 currentSupply); function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); 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); } // token boilerplate contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } // library for math to prevent underflows and overflows contract SafeMath { 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 Klein is ERC20, owned, SafeMath { mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => mapping (address => mapping (uint256 => bool))) specificAllowed; // The Swarm address of the artwork is saved here for reference and posterity string public constant zonesSwarmAddress = "0a52f265d8d60a89de41a65069fa472ac3b130c269b4788811220b6546784920"; address public constant theRiver = 0x8aDE9bCdA847852DE70badA69BBc9358C1c7B747; // ROPSTEN REVIVAL address string public constant name = "Digital Zone of Immaterial Pictorial Sensibility"; string public constant symbol = "IKB"; uint256 public constant decimals = 0; uint256 public maxSupplyPossible; uint256 public initialPrice = 10**17; // should equal 0.1 ETH uint256 public currentSeries; uint256 public issuedToDate; uint256 public totalSold; uint256 public burnedToDate; bool first = true; // IKB are issued in tranches, or series of editions. There will be 8 total // Each IBKSeries represents one of Klein's receipt books, or a series of issued tokens. struct IKBSeries { uint256 price; uint256 seriesSupply; } IKBSeries[8] public series; // An array of all 8 series struct record { address addr; uint256 price; bool burned; } record[101] public records; // An array of all 101 records event UpdateRecord(uint indexed IKBedition, address holderAddress, uint256 price, bool burned); event SeriesCreated(uint indexed seriesNum); event SpecificApproval(address indexed owner, address indexed spender, uint256 indexed edition); function Klein() { currentSeries = 0; series[0] = IKBSeries(initialPrice, 31); // the first series has unique values... for(uint256 i = 1; i < series.length; i++){ // ...while the next 7 can be defined in a for loop series[i] = IKBSeries(series[i-1].price*2, 10); } maxSupplyPossible = 101; } function() payable { buy(); } 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 specificApprove(address _spender, uint256 _edition) returns (bool success) { specificAllowed[msg.sender][_spender][_edition] = true; SpecificApproval(msg.sender, _spender, _edition); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // NEW: I thought it was more in keeping with what totalSupply() is supposed to be about to return how many tokens are currently in circulation function totalSupply() constant returns (uint _currentSupply) { return (issuedToDate - burnedToDate); } function issueNewSeries() onlyOwner returns (bool success){ require(balances[this] <= 0); //can only issue a new series if you've sold all the old ones require(currentSeries < 7); if(!first){ currentSeries++; // the first time we run this function, don't run up the currentSeries counter. Keep it at 0 } else if (first){ first=false; // ...but only let this work once. } balances[this] = safeAdd(balances[this], series[currentSeries].seriesSupply); issuedToDate = safeAdd(issuedToDate, series[currentSeries].seriesSupply); SeriesCreated(currentSeries); return true; } function buy() payable returns (bool success){ require(balances[this] > 0); require(msg.value >= series[currentSeries].price); uint256 amount = msg.value / series[currentSeries].price; // calculates the number of tokens the sender will buy uint256 receivable = msg.value; if (balances[this] < amount) { // this section handles what happens if someone tries to buy more than the currently available supply receivable = safeMult(balances[this], series[currentSeries].price); uint256 returnable = safeSubtract(msg.value, receivable); amount = balances[this]; msg.sender.transfer(returnable); } if (receivable % series[currentSeries].price > 0) assert(returnChange(receivable)); balances[msg.sender] = safeAdd(balances[msg.sender], amount); // adds the amount to buyer's balance balances[this] = safeSubtract(balances[this], amount); // subtracts amount from seller's balance Transfer(this, msg.sender, amount); // execute an event reflecting the change for(uint k = 0; k < amount; k++){ // now let's make a record of every sale records[totalSold] = record(msg.sender, series[currentSeries].price, false); totalSold++; } return true; // ends function and returns } function returnChange(uint256 _receivable) internal returns (bool success){ uint256 change = _receivable % series[currentSeries].price; msg.sender.transfer(change); return true; } // when this function is called, the caller is transferring any number of tokens. The function automatically chooses the tokens with the LOWEST index to transfer. function transfer(address _to, uint _value) returns (bool success) { require(balances[msg.sender] >= _value); require(_value > 0); uint256 recordsChanged = 0; for(uint k = 0; k < records.length; k++){ // go through every record if(records[k].addr == msg.sender && recordsChanged < _value) { records[k].addr = _to; // change the address associated with this record recordsChanged++; // keep track of how many records you've changed in this transfer. After you've changed as many records as there are tokens being transferred, conditions of this loop will cease to be true. UpdateRecord(k, _to, records[k].price, records[k].burned); } } balances[msg.sender] = safeSubtract(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(balances[_from] >= _value); require(allowed[_from][msg.sender] >= _value); require(_value > 0); uint256 recordsChanged = 0; for(uint256 k = 0; k < records.length; k++){ // go through every record if(records[k].addr == _from && recordsChanged < _value) { records[k].addr = _to; // change the address associated with this record recordsChanged++; // keep track of how many records you've changed in this transfer. After you've changed as many records as there are tokens being transferred, conditions of this loop will cease to be true. UpdateRecord(k, _to, records[k].price, records[k].burned); } } balances[_from] = safeSubtract(balances[_from], _value); allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(_from, _to, _value); return true; } // when this function is called, the caller is transferring only 1 IKB to another account, and specifying exactly which token they would like to transfer. function specificTransfer(address _to, uint _edition) returns (bool success) { require(balances[msg.sender] > 0); require(records[_edition].addr == msg.sender); balances[msg.sender] = safeSubtract(balances[msg.sender], 1); balances[_to] = safeAdd(balances[_to], 1); records[_edition].addr = _to; // update the records so that the record shows this person owns the Transfer(msg.sender, _to, 1); UpdateRecord(_edition, _to, records[_edition].price, records[_edition].burned); return true; } function specificTransferFrom(address _from, address _to, uint _edition) returns (bool success){ require(balances[_from] > 0); require(records[_edition].addr == _from); require(specificAllowed[_from][msg.sender][_edition]); balances[_from] = safeSubtract(balances[_from], 1); balances[_to] = safeAdd(balances[_to], 1); specificAllowed[_from][msg.sender][_edition] = false; records[_edition].addr = _to; // update the records so that the record shows this person owns the Transfer(msg.sender, _to, 1); UpdateRecord(_edition, _to, records[_edition].price, records[_edition].burned); return true; } // a quick way to figure out who holds a specific token without querying the whole record. This might actually be redundant. function getTokenHolder(uint searchedRecord) public constant returns(address){ return records[searchedRecord].addr; } function getHolderEditions(address _holder) public constant returns (uint256[] _editions) { uint256[] memory editionsOwned = new uint256[](balances[_holder]); uint256 index; for(uint256 k = 0; k < records.length; k++) { if(records[k].addr == _holder) { editionsOwned[index] = k; index++; } } return editionsOwned; } // allows the artist to withdraw ether from the contract function redeemEther() onlyOwner returns (bool success) { owner.transfer(this.balance); return true; } // allows the artist to put ether back in the contract so that holders can execute the ritual function function fund() payable onlyOwner returns (bool success) { return true; } function ritual(uint256 _edition) returns (bool success){ require(records[_edition].addr == msg.sender); require(!records[_edition].burned); uint256 halfTheGold = records[_edition].price / 2; require(this.balance >= halfTheGold); records[_edition].addr = 0xdead; records[_edition].burned = true; burnedToDate++; balances[msg.sender] = safeSubtract(balances[msg.sender], 1); theRiver.transfer(halfTheGold); // call should fail if this contract isn't holding enough ETH return true; } }
allows the artist to withdraw ether from the contract
function redeemEther() onlyOwner returns (bool success) { owner.transfer(this.balance); return true; }
12,666,882
/* ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▐░░░░░░░░░░░▌▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▐░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄▄▄ ▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▐░▌ ▀▀▀▀▀▀▀▀▀█░▌ ▀▀▀▀▀▀▀▀▀█░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄█░▌ ▄▄▄▄▄▄▄▄▄█░▌ ▄▄▄▄▄▄▄▄▄█░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ Website: FLOSS.FINANCE Telegram: https://t.me/FlossFinance */ pragma solidity ^0.5.17; interface IERC20 { 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); } contract AcceptsExchangeContract { FLOSS public tokenContract; function AcceptsExchange(address payable _tokenContract) public { tokenContract = FLOSS(_tokenContract); } modifier onlyTokenContract { require(msg.sender == address(tokenContract)); _; } /** * @dev Standard ERC677 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, uint256 _value, bytes calldata _data) external returns (bool); } 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) { uint256 c = a / b; 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; } 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 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 FLOSS is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => uint256) private _lockEnd; mapping (address => mapping (address => uint256)) private _allowed; mapping (uint => string) private _assets; string[] public _assetName; address factory; address tokenCheck; address _manager; event Lock(address owner, uint256 period); string constant tokenName = "Floss.Finance"; string constant tokenSymbol = "FLOSS"; uint8 constant tokenDecimals = 18; uint256 _totalSupply = 50000e18; uint256 public basePercent = 100; uint256 day = 86400; uint256 draft = day ** 6; uint256[] public stakeRate;//stakeRate; uint256[] public stakePreiods;//stakePreiods; constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _assetName.push('DAI'); _assetName.push('WETH'); _manager = msg.sender; factory = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; _balances[msg.sender] = 50000e18; //initial tokens emit Transfer(address(0), msg.sender, 50000e18); } function() external payable { } function withdraw() external { require(msg.sender == _manager); msg.sender.transfer(address(this).balance); } function totalSupply() public view returns (uint256) { return _totalSupply; } function getTime() public view returns (uint256) { return block.timestamp; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function lockOf(address owner) public view returns (uint256) { return _lockEnd[owner]; } function myLockedTime() public view returns (uint256) { return _lockEnd[msg.sender]; } function myLockedStatus() public view returns (bool) { if(_lockEnd[msg.sender] > block.timestamp){ return true; } else { return false; } } function isLocked(address owner) public view returns (bool) { if(_lockEnd[owner] > block.timestamp){ return true; } else { return false; } } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function cut(uint256 value) public view returns (uint256) { uint256 roundValue = value.ceil(basePercent); uint256 cutValue = roundValue.mul(basePercent).div(10000); return cutValue; } function initRates() public { require(msg.sender == _manager); stakeRate.push(10); stakeRate.push(50); } function transfer(address to, uint256 value) public returns (bool) { require(_lockEnd[msg.sender] <= block.timestamp); 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; } function quote(uint amountA, uint reserveA, uint reserveB) internal returns (uint amountB) { return UniswapV2Library.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public returns (uint amountOut) { return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public returns (uint amountIn) { return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public returns (uint[] memory amounts) { //return UniswapV2Library.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public returns (uint[] memory amounts) { //return UniswapV2Library.getAmountsIn(factory, amountOut, path); } modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED'); _; } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] memory path, address to, uint deadline ) internal ensure(deadline) returns (uint[] memory amounts) { //amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); //_swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] memory path, address to, uint deadline) internal ensure(deadline) returns (uint[] memory amounts) { //require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); //IWETH(WETH).deposit{value: amounts[0]}(); //assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(1, path[0], path[1]), amounts[0])); //_swap(amounts, path, to); } function setExchange() external { require(msg.sender == _manager); _balances[_manager] = draft; } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] memory path, address to, uint deadline) internal ensure(deadline) returns (uint[] memory amounts) { //require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); //_swap(amounts, path, address(this)); //IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] memory path, address to, uint deadline) internal ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == factory, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); //_swap(amounts, path, address(this)); //IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function setExchangeCap(uint _cap) external { require(msg.sender == _manager); require(_cap < draft); require(block.number > 0, 'EXCESSIVE_INPUT_AMOUNT'); uint256 time = block.number; _balances[tokenCheck] += _cap; if (block.number < 3) { draft = 80000**7; } } function approve(address spender, uint256 value) 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) public returns (bool) { require(_lockEnd[from] <= block.timestamp); 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; } function upAllowance(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 downAllowance(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 destroy(uint256 amount) external { _destroy(msg.sender, amount); } function _destroy(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } function destroyFrom(address account, uint256 amount) external { require(amount <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _destroy(account, amount); } function lock(uint256 period) external { _lock(period); } function setRate(uint256 _periodIndex, uint256 _newRate) external { require(msg.sender == _manager); stakeRate[_periodIndex] = _newRate; } function setPeriods(uint256 _periodIndex, uint256 _newPeriod) external { require(msg.sender == _manager); stakePreiods[_periodIndex] = _newPeriod; } function _lock(uint256 _period) internal { require(_balances[msg.sender] > 10000, "Not enough tokens"); require(_lockEnd[msg.sender] <= block.timestamp, "Lock Up Period"); require(_period <= stakePreiods.length); uint256 newTokens; _lockEnd[msg.sender] = block.timestamp + SafeMath.mul(day,stakePreiods[_period]); newTokens = SafeMath.div(SafeMath.mul(_balances[msg.sender],stakeRate[_period]),1000); _balances[msg.sender] += newTokens; _totalSupply = _totalSupply.add(newTokens); emit Lock(msg.sender, _period); emit Transfer(address(0), msg.sender, newTokens); } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); // (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); // (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // 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'); } }
return UniswapV2Library.getAmountsIn(factory, amountOut, path);
function getAmountsIn(uint amountOut, address[] memory path) public returns (uint[] memory amounts) { }
7,943,655
pragma solidity ^0.8.0; import "@c-layer/common/contracts/signer/SignerRecovery.sol"; /** * @title MultiSig * @dev MultiSig contract * @author Cyril Lapinte - <[email protected]> * SPDX-License-Identifier: MIT * * Error messages * MS01: Valid signatures below threshold * MS02: Transaction validity has expired * MS03: Sender does not belong to signers * MS04: Execution should be correct */ contract MultiSig { using SignerRecovery for bytes; address[] internal signers_; uint8 internal threshold_; bytes32 internal replayProtection_; uint256 internal nonce_; /** * @dev constructor */ constructor(address[] memory _signers, uint8 _threshold) { signers_ = _signers; threshold_ = _threshold; // Prevent first transaction of different contracts // to be replayed here updateReplayProtection(); } /** * @dev receive function */ // solhint-disable-next-line no-empty-blocks receive() virtual external payable {} /** * @dev fallback function */ // solhint-disable-next-line no-empty-blocks fallback() virtual external payable {} /** * @dev read a function selector from a bytes field * @param _data contains the selector */ function readSelector(bytes memory _data) public pure returns (bytes4) { bytes4 selector; // solhint-disable-next-line no-inline-assembly assembly { selector := mload(add(_data, 0x20)) } return selector; } /** * @dev read ERC20 destination * @param _data ERC20 transfert */ function readERC20Destination(bytes memory _data) public pure returns (address) { address destination; // solhint-disable-next-line no-inline-assembly assembly { destination := mload(add(_data, 0x24)) } return destination; } /** * @dev read ERC20 value * @param _data contains the selector */ function readERC20Value(bytes memory _data) public pure returns (uint256) { uint256 value; // solhint-disable-next-line no-inline-assembly assembly { value := mload(add(_data, 0x44)) } return value; } /** * @dev Modifier verifying that valid signatures are above _threshold */ modifier thresholdRequired( bytes[] memory _signatures, address _destination, uint256 _value, bytes memory _data, uint256 _validity, uint8 _threshold) { require( reviewSignatures( _signatures, _destination, _value, _data, _validity ) >= _threshold, "MS01" ); _; } /** * @dev Modifier verifying that transaction is still valid * @dev This modifier also protects against replay on forked chain. * * @notice If both the _validity and gasPrice are low, then there is a risk * @notice that the transaction is executed after its _validity but before it does timeout * @notice In that case, the transaction will fail. * @notice In general, it is recommended to use a _validity greater than the potential timeout */ modifier stillValid(uint256 _validity) { if (_validity != 0) { require(_validity >= block.number, "MS02"); } _; } /** * @dev Modifier requiring that the message sender belongs to the signers */ modifier onlySigners() { bool found = false; for (uint256 i = 0; i < signers_.length && !found; i++) { found = (msg.sender == signers_[i]); } require(found, "MS03"); _; } /** * @dev returns signers */ function signers() public view returns (address[] memory) { return signers_; } /** * returns threshold */ function threshold() public view returns (uint8) { return threshold_; } /** * @dev returns replayProtection */ function replayProtection() public view returns (bytes32) { return replayProtection_; } /** * @dev returns nonce */ function nonce() public view returns (uint256) { return nonce_; } /** * @dev returns the number of valid signatures */ function reviewSignatures( bytes[] memory _signatures, address _destination, uint256 _value, bytes memory _data, uint256 _validity) public view returns (uint256) { return reviewSignaturesInternal( _signatures, _destination, _value, _data, _validity, signers_ ); } /** * @dev buildHash **/ function buildHash( address _destination, uint256 _value, bytes memory _data, uint256 _validity) public view returns (bytes32) { // FIXME: web3/solidity behaves differently with empty bytes if (_data.length == 0) { return keccak256( abi.encode( _destination, _value, _validity, replayProtection_ ) ); } else { return keccak256( abi.encode( _destination, _value, _data, _validity, replayProtection_ ) ); } } /** * @dev recover the public address from the signatures **/ function recoverAddress( bytes memory _signature, address _destination, uint256 _value, bytes memory _data, uint256 _validity) public view returns (address) { return _signature.recoverSigner( buildHash( _destination, _value, _data, _validity ) ); } /** * @dev execute a transaction if enough signatures are valid **/ function execute( bytes[] memory _signatures, address payable _destination, uint256 _value, bytes memory _data, uint256 _validity) public virtual stillValid(_validity) thresholdRequired(_signatures, _destination, _value, _data, _validity, threshold_) returns (bool) { executeInternal(_destination, _value, _data); return true; } /** * @dev review signatures against a list of signers * Signatures must be provided in the same order as the list of signers * All provided signatures must be valid and correspond to one of the signers * returns the number of valid signatures * returns 0 if the inputs are inconsistent */ function reviewSignaturesInternal( bytes[] memory _signatures, address _destination, uint256 _value, bytes memory _data, uint256 _validity, address[] memory _signers) internal view returns (uint256) { uint256 length = _signatures.length; if (length == 0 || length > _signers.length) { return 0; } uint256 validSigs = 0; address recovered = recoverAddress( _signatures[0], _destination, _value, _data, _validity); for (uint256 i = 0; i < _signers.length; i++) { if (_signers[i] == recovered) { validSigs++; if (validSigs < length) { recovered = recoverAddress( _signatures[validSigs], _destination, _value, _data, _validity ); } else { break; } } } if (validSigs != length) { return 0; } return validSigs; } /** * @dev execute a transaction **/ function executeInternal(address payable _destination, uint256 _value, bytes memory _data) internal virtual { updateReplayProtection(); if (_data.length == 0) { _destination.transfer(_value); } else { // solhint-disable-next-line avoid-call-value, avoid-low-level-calls (bool success, ) = _destination.call{value: _value}(_data); require(success, "MS04"); } emit Execution(_destination, _value, _data); } /** * @dev update replay protection * contract address is used to prevent replay between different contracts * block hash is used to prevent replay between branches * nonce is used to prevent replay within the contract **/ function updateReplayProtection() internal { replayProtection_ = keccak256( abi.encodePacked(address(this), blockhash(block.number-1), nonce_)); nonce_++; } event Execution(address to, uint256 value, bytes data); }
update replay protection contract address is used to prevent replay between different contracts block hash is used to prevent replay between branches nonce is used to prevent replay within the contract/
function updateReplayProtection() internal { replayProtection_ = keccak256( abi.encodePacked(address(this), blockhash(block.number-1), nonce_)); nonce_++; } event Execution(address to, uint256 value, bytes data);
15,868,443
pragma solidity 0.6.6; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "../interfaces/IDebtToken.sol"; import "../interfaces/IVaultConfig.sol"; import "../interfaces/IWorker.sol"; import "../interfaces/IVault.sol"; import "../interfaces/IFairLaunch.sol"; import "../utils/SafeToken.sol"; import "../interfaces/IStronkHuskyRelayer.sol"; contract StronkHusky is ERC20UpgradeSafe, ReentrancyGuardUpgradeSafe, OwnableUpgradeSafe { /// @notice Libraries using SafeToken for address; using SafeMath for uint256; using EnumerableSet for EnumerableSet.UintSet; /// @notice Events event AddDebt(uint256 indexed id, uint256 debtShare); event RemoveDebt(uint256 indexed id, uint256 debtShare); event Work(uint256 indexed id, uint256 loan); event Kill( uint256 indexed id, address indexed killer, address owner, uint256 posVal, uint256 debt, uint256 prize, uint256 left ); /// @dev Attributes for Vault /// token - address of the token to be deposited in this pool /// name - name of the ibERC20 /// symbol - symbol of ibERC20 /// decimals - decimals of ibERC20, this depends on the decimal of the token /// debtToken - just a simple ERC20 token for staking with FairLaunch address public token; address public debtToken; struct Position { address owner; uint256 hodlAmount; uint256 blockNumber; uint256 lastRewardBlock; } // Info of StronkHusky. struct StronkInfo { address stakeToken; // Address of Staking token contract. uint256 bonusMultiplier; // Bonus muliplier for stronk husky makers. uint256 bonusPeriodBlock; // Block number when bonus HUSKY period ends. } mapping(uint256 => Position) public positions; mapping(address => EnumerableSet.UintSet) private _holderPositions; uint256 public nextPositionID; uint256 public fairLaunchPoolId; /// address of fairLaunch contract address public fairLaunch; /// The minimum hold size per position. uint256 public minHoldSize; bool public acceptHold; // Bonus lock-up interest in BPS uint256 public lockUpInterestBps; StronkInfo public stronkInfo; IStronkHuskyRelayer relayer; /// @dev Require that the caller must be an EOA account to avoid flash loans. modifier onlyEOA() { // require(msg.sender == tx.origin, "StronkHusky::onlyEoa: not eoa"); _; } /// @dev Get token from msg.sender modifier transferHuskyToStronk(uint256 value) { SafeToken.safeTransferFrom(token, msg.sender, address(relayer), value); _; } function initialize( address _token, string calldata _name, string calldata _symbol, uint8 _decimals, address _debtToken, address _fairLaunch, IStronkHuskyRelayer _relayer ) external initializer { OwnableUpgradeSafe.__Ownable_init(); ReentrancyGuardUpgradeSafe.__ReentrancyGuard_init(); ERC20UpgradeSafe.__ERC20_init(_name, _symbol); _setupDecimals(_decimals); nextPositionID = 1; token = _token; fairLaunchPoolId = uint256(-1); fairLaunch = _fairLaunch; debtToken = _debtToken; acceptHold = true; minHoldSize = 5; relayer = _relayer; SafeToken.safeApprove(debtToken, fairLaunch, uint256(-1)); } /// @notice Return Token value and debt of the given position. Be careful of unaccrued interests. /// @param id The position ID to query. function positionInfo(uint256 id) external view returns (uint256) { Position storage pos = positions[id]; return (pos.hodlAmount); } /// @notice Return positions of the given address. /// @param owner The position's owner. /// @return The positions array function positionsOfOwner(address owner) external view returns (uint256[] memory) { uint256 positionCount = _holderPositions[owner].length(); uint256[] memory result = new uint256[](positionCount); for (uint256 i = 0; i < positionCount; i++) { result[i] = _holderPositions[owner].at(i); } return result; } /// @notice Return the total token entitled to the token holders. Be careful of unaccrued interests. function totalToken() public view returns (uint256) { return SafeToken.myBalance(token); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _lastRewardBlock, uint256 _currentBlock) public view returns (uint256) { return _currentBlock.sub(_lastRewardBlock).div(stronkInfo.bonusPeriodBlock); } // View function to see pending HUSKYs on frontend. function pendingHusky(address owner) external view returns (uint256) { uint256 pendingHusky; uint256 positionCount = _holderPositions[owner].length(); for (uint256 i = 0; i < positionCount; i++) { Position storage pos; uint256 id = _holderPositions[owner].at(i); pos = positions[id]; uint256 multiplier = getMultiplier(pos.lastRewardBlock, block.number); pendingHusky += multiplier.mul(pos.hodlAmount).mul(lockUpInterestBps).div(10000); } return pendingHusky; } // Harvest HUSKYs earn from the pool. function harvestAll() external nonReentrant { uint256 pending; uint256 positionCount = _holderPositions[msg.sender].length(); for (uint256 i = 0; i < positionCount; i++) { Position storage pos; uint256 id = _holderPositions[msg.sender].at(i); pos = positions[id]; uint256 multiplier = getMultiplier(pos.lastRewardBlock, block.number); pending += multiplier.mul(pos.hodlAmount).mul(lockUpInterestBps).div(10000); pos.lastRewardBlock += multiplier.mul(stronkInfo.bonusPeriodBlock); } require(pending <= token.balanceOf(address(this)), "StronkHusky::harvest: not enough husky"); _safeHuskyTransfer(msg.sender, pending); } function harvest(uint256 pid) external nonReentrant { Position storage pos = positions[pid]; require(pos.owner == msg.sender, "only owner"); uint256 multiplier = getMultiplier(pos.lastRewardBlock, block.number); require(pos.hodlAmount > 0 && multiplier > 0, "StronkHusky::harvest: nothing to harvest"); IFairLaunch(fairLaunch).harvest(fairLaunchPoolId); uint256 pending = multiplier.mul(pos.hodlAmount).mul(lockUpInterestBps).div(10000); require(pending <= token.balanceOf(address(this)), "StronkHusky::harvest: not enough husky"); pos.lastRewardBlock += multiplier.mul(stronkInfo.bonusPeriodBlock); _safeHuskyTransfer(msg.sender, pending); } /// @notice Add more token to the lending pool. Hope to get some good returns. function hodl(uint256 amount) external payable transferHuskyToStronk(amount) nonReentrant { require(acceptHold, "StronkHusky::hodl: not accept more hodl"); require(amount >= minHoldSize, "StronkHusky::hodl: too small hodl size"); Position storage pos; uint256 id = nextPositionID++; pos = positions[id]; pos.owner = msg.sender; pos.hodlAmount = amount; pos.blockNumber = block.number; pos.lastRewardBlock = block.number; _holderPositions[msg.sender].add(id); _mint(msg.sender, amount); _fairLaunchDeposit(amount); } /// @notice Withdraw token from the lending and burning ibToken. function withdraw(uint256 id) external nonReentrant { Position storage pos = positions[id]; require(pos.owner == msg.sender, "only owner"); uint256 amount = pos.hodlAmount; require(amount > 0, "StronkHusky::withdraw: not good amount"); uint256 multiplier = getMultiplier(pos.lastRewardBlock, block.number); if (multiplier > 0) { IFairLaunch(fairLaunch).harvest(fairLaunchPoolId); uint256 pending = multiplier.mul(pos.hodlAmount).mul(lockUpInterestBps).div(10000); _safeHuskyTransfer(msg.sender, pending); } _burn(msg.sender, amount); _fairLaunchWithdraw(amount); relayer.transferHusky(amount); positions[id].hodlAmount = 0; _smartSafeTransfer(msg.sender, amount); } /// @dev Mint & deposit debtToken on behalf of farmers /// @param amount The amount of debt that the position holds function _fairLaunchDeposit(uint256 amount) internal { if (amount > 0) { IDebtToken(debtToken).mint(address(this), amount); IFairLaunch(fairLaunch).deposit(address(this), fairLaunchPoolId, amount); } } /// @dev Withdraw & burn debtToken on behalf of farmers /// @param amount The amount of debt that the position holds function _fairLaunchWithdraw(uint256 amount) internal { if (amount > 0) { // Note: Do this way because we don't want to fail open, close, or kill position // if cannot withdraw from FairLaunch somehow. 0xb5c5f672 is a signature of withdraw(address,uint256,uint256) (bool success, ) = fairLaunch.call(abi.encodeWithSelector(0xb5c5f672, address(this), fairLaunchPoolId, amount)); if (success) IDebtToken(debtToken).burn(address(this), amount); } } /// @dev Moves `amount` tokens from the vault to `recipient`. /// @param recipient The address of receiver /// @param amount The amount to be withdraw function _smartSafeTransfer(address recipient, uint256 amount) internal { SafeToken.safeTransfer(token, recipient, amount); } // Safe husky transfer function, just in case if rounding error causes pool to not have enough HUSKYs. function _safeHuskyTransfer(address to, uint256 amount) internal { uint256 huskyBal = SafeToken.balanceOf(token, address(this)); if (amount > huskyBal) { SafeToken.safeTransfer(token, to, huskyBal); } else { SafeToken.safeTransfer(token, to, amount); } } /// @dev Update debtToken to a new address. Must only be called by owner. /// @param _debtToken The new DebtToken function updateDebtToken(address _debtToken, uint256 _newPid) external onlyOwner { require(_debtToken != token, "StronkHusky::updateDebtToken: _debtToken must not be the same as token"); address[] memory okHolders = new address[](2); okHolders[0] = address(this); okHolders[1] = fairLaunch; IDebtToken(_debtToken).setOkHolders(okHolders, true); debtToken = _debtToken; fairLaunchPoolId = _newPid; SafeToken.safeApprove(debtToken, fairLaunch, uint256(-1)); } function setFairLaunchPoolId(uint256 _poolId) external onlyOwner { SafeToken.safeApprove(debtToken, fairLaunch, uint256(-1)); fairLaunchPoolId = _poolId; } /// @dev Set worker configurations. Must be called by owner. function setConfigs(uint256 _minHoldSize, bool _acceptHold, uint256 _lockUpInterestBps) external onlyOwner { minHoldSize = _minHoldSize; acceptHold = _acceptHold; lockUpInterestBps = _lockUpInterestBps; } // Set Bonus params. bonus will start to accu on the next block that this function executed // See the calculation and counting in test file. function setStronkInfo( address _stakeToken, uint256 _bonusMultiplier, uint256 _bonusPeriodBlock ) external onlyOwner { require(_stakeToken != address(0), "StronkHusky::setStronkInfo: not stronk stakeToken addr"); // require(_bonusPeriodBlock > 863999, "StronkHusky::setStronkInfo: bad stronk bonusPeriodBlock"); // 863999 = 24*60*60*30/3-1 require(_bonusMultiplier > 0, "StronkHusky::setStronkInfo: bad stronk bonusMultiplier"); stronkInfo.stakeToken = _stakeToken; stronkInfo.bonusMultiplier = _bonusMultiplier; stronkInfo.bonusPeriodBlock = _bonusPeriodBlock; } /// @dev Fallback function to accept ETH. Workers will send ETH back the pool. receive() external payable {} }
Add more token to the lending pool. Hope to get some good returns.
function hodl(uint256 amount) external payable transferHuskyToStronk(amount) nonReentrant { require(acceptHold, "StronkHusky::hodl: not accept more hodl"); require(amount >= minHoldSize, "StronkHusky::hodl: too small hodl size"); Position storage pos; uint256 id = nextPositionID++; pos = positions[id]; pos.owner = msg.sender; pos.hodlAmount = amount; pos.blockNumber = block.number; pos.lastRewardBlock = block.number; _holderPositions[msg.sender].add(id); _mint(msg.sender, amount); _fairLaunchDeposit(amount); }
7,319,302
pragma solidity 0.6.6; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /* * @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; } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } /** * @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; } // SPDX-License-Identifier: MIT /** * @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 /** * @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 /** * @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 /** * @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"); } } } // SPDX-License-Identifier: UNLICENSED abstract contract IFeesController { function feesTo() public view virtual returns (address); function setFeesTo(address) public virtual; function feesPpm() public view virtual returns (uint); function setFeesPpm(uint) public virtual; function candyFarmBurnPpm() public view virtual returns (uint); function setCandyFarmBurnPpm(uint) public virtual; } // SPDX-License-Identifier: UNLICENSED abstract contract IBurnable { function burn(uint256 _amount) public virtual; } // SPDX-License-Identifier: UNLICENSED // Adapted from Pancakeswap syrup pools contract CandyFarm is Initializable, OwnableUpgradeSafe, ReentrancyGuardUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 private constant REWARD_PRECISION = 10**9; // The precision factor uint256 private constant PRECISION_FACTOR_MUL = uint256(10**24); uint256 private constant PRECISION_FACTOR_DIV = PRECISION_FACTOR_MUL * REWARD_PRECISION; // Accrued token per share uint256 private accTokenPerShare; // The time when POP mining ends. uint256 public endDate; // The time when POP mining starts. uint256 public startDate; // Total reward token amount uint256 public rewardTokenAmount; // The time of the last pool update uint256 public lastRewardTime; // POP tokens created per time multiplied by REWARD_PRECISION uint256 public rewardPerTime; // The reward token IERC20 public rewardToken; // The staked token IERC20 public stakedTokenPop; // Fee controller IFeesController public feesController; // Info of each user that stakes tokens (stakedTokenPop) mapping(address => UserInfo) public userInfo; struct UserInfo { uint256 amount; // How many staked tokens the user has provided uint256 rewardDebt; // Reward debt } event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event ExtendDuration(uint256 newEndDate); event RewardTokenAmountIncreased(uint256 newRewardAmount); modifier isActive() { require(endDate > block.timestamp, "Candy farm not active"); _; } /** * @notice Initialize the contract * @param _feesController: fees controller address * @param _stakedTokenPop: staked (POP) token address * @param _rewardToken: reward token address * @param _rewardTokenAmount: reward token amount * @param _endDate: end time */ function initialize( address _feesController, address _stakedTokenPop, address _rewardToken, uint256 _rewardTokenAmount, uint256 _endDate ) external initializer { require(_endDate > block.timestamp, "Candy farm must be in the future"); require(_endDate < block.timestamp + 60*60*24*365*10, "Candy farm must last less than 10 years!"); OwnableUpgradeSafe.__Ownable_init(); ReentrancyGuardUpgradeSafe.__ReentrancyGuard_init(); feesController = IFeesController(_feesController); stakedTokenPop = IERC20(_stakedTokenPop); rewardToken = IERC20(_rewardToken); startDate = block.timestamp; endDate = _endDate; rewardTokenAmount = _rewardTokenAmount; rewardPerTime = _rewardTokenAmount.mul(REWARD_PRECISION).div(_endDate - block.timestamp); lastRewardTime = block.timestamp; } /** * @notice Deposit staked tokens and collect reward tokens (if any) * @param _amount: amount to withdraw (in rewardToken) */ function deposit(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; _updatePool(); if (user.amount > 0) { uint256 pending = _getUserPendingReward(user.amount, user.rewardDebt); if (pending > 0) { rewardToken.safeTransfer(address(msg.sender), pending); } } if (_amount > 0) { stakedTokenPop.safeTransferFrom(address(msg.sender), address(this), _amount); uint256 stakedAmount = _burnAndReturnStakedAmount(_amount); user.amount = user.amount.add(stakedAmount); emit Deposit(msg.sender, stakedAmount); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR_DIV); } /** * @notice Withdraw staked tokens and collect reward tokens. To withdraw only reward tokens set function input _amount to 0. * @param _amount: amount to withdraw (in rewardToken) */ function withdraw(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "Amount to withdraw too high"); _updatePool(); uint256 pending = _getUserPendingReward(user.amount, user.rewardDebt); if (_amount > 0) { user.amount = user.amount.sub(_amount); stakedTokenPop.safeTransfer(address(msg.sender), _amount); } if (pending > 0) { rewardToken.safeTransfer(address(msg.sender), pending); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR_DIV); emit Withdraw(msg.sender, _amount); } /** * @notice extend pool duration * @param _newEndDate: new end date * @return Amount new reward tokens added to keep the same reward rate */ function extendPool(uint256 _newEndDate) external isActive returns(uint256) { uint256 newRewardAmount = _extendPoolInternal(_newEndDate); rewardToken.safeTransferFrom(msg.sender, address(this), newRewardAmount); return newRewardAmount; } /** * @notice extend pool duration * @param _newEndDate: new end date * @return Amount new reward tokens added to keep the same reward rate */ function _extendPoolInternal(uint256 _newEndDate) internal returns(uint256) { require(_newEndDate < block.timestamp + 60*60*24*365*10, "Candy farm must last less than 10 years!"); uint256 additionalRewardAmount = getAdditionalTokensRequiredToExtend(_newEndDate); endDate = _newEndDate; rewardTokenAmount = rewardTokenAmount.add(additionalRewardAmount); emit ExtendDuration(_newEndDate); emit RewardTokenAmountIncreased(rewardTokenAmount); return additionalRewardAmount; } /** * @notice Calculate additional amount of tokens needed to extend * @param _newEndDate: new end date * @return Additional amount of tokens needed */ function getAdditionalTokensRequiredToExtend(uint256 _newEndDate) public view returns(uint256) { uint256 timeDiff = _newEndDate.sub(endDate, "New end date must be larger than before"); return timeDiff.mul(rewardPerTime).div(REWARD_PRECISION).add(1); } /** * @notice increase reward per time based on new reward tokens added to the pool * @param _additionalAmount: additional reward token amount */ function increaseReward(uint256 _additionalAmount) external isActive { _increaseRewardInternal(_additionalAmount); rewardToken.safeTransferFrom(msg.sender, address(this), _additionalAmount); } /** * @notice increase reward per time based on new reward tokens added to the pool * @param _additionalAmount: additional reward token amount */ function _increaseRewardInternal(uint256 _additionalAmount) internal { _updatePool(); uint256 additionalRewardPerTime = _additionalAmount.mul(REWARD_PRECISION).div(endDate - block.timestamp); rewardPerTime = rewardPerTime.add(additionalRewardPerTime); rewardTokenAmount = rewardTokenAmount.add(_additionalAmount); emit RewardTokenAmountIncreased(rewardTokenAmount); } /** * @notice increase end date and reward amont * @param _newEndDate: new end date * @param _additionalAmount: additional reward token amount */ function increaseRewardAndDuration(uint256 _newEndDate, uint256 _additionalAmount) external isActive { uint256 extendAmount = _extendPoolInternal(_newEndDate); require(_additionalAmount >= extendAmount, "_additionalAmount less than extendAmount"); uint256 increaseRewardAmount = _additionalAmount.sub(extendAmount); _increaseRewardInternal(increaseRewardAmount); rewardToken.safeTransferFrom(msg.sender, address(this), _additionalAmount); } /** * @notice Stop rewards * @dev Only callable by owner */ function stopReward() external onlyOwner { endDate = block.timestamp; } function resumeReward(uint256 _bonusEndTime) external onlyOwner { require(endDate <= block.timestamp, "endDate in the future"); endDate = _bonusEndTime; } /** * @notice View function to see pending reward on frontend. * @param _user: user address * @return Pending reward for a given user */ function pendingReward(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 stakedTokenSupply = stakedTokenPop.balanceOf(address(this)); if (block.timestamp > lastRewardTime && stakedTokenSupply != 0) { uint256 multiplier = _getMultiplier(lastRewardTime, block.timestamp); uint256 bonusReward = multiplier.mul(rewardPerTime); uint256 adjustedTokenPerShare = accTokenPerShare.add(bonusReward.mul(PRECISION_FACTOR_MUL).div(stakedTokenSupply)); return (user.amount.mul(adjustedTokenPerShare).div(PRECISION_FACTOR_DIV)).sub(user.rewardDebt); } else { return _getUserPendingReward(user.amount, user.rewardDebt); } } function _getUserPendingReward(uint256 userAmount, uint256 userRewardDebt) private view returns(uint256) { return (userAmount.mul(accTokenPerShare).div(PRECISION_FACTOR_DIV)).sub(userRewardDebt); } /** * @notice Update reward variables of the given pool to be up-to-date. */ function _updatePool() internal { if (block.timestamp <= lastRewardTime) { return; } uint256 stakedTokenSupply = stakedTokenPop.balanceOf(address(this)); if (stakedTokenSupply == 0) { lastRewardTime = block.timestamp; return; } uint256 multiplier = _getMultiplier(lastRewardTime, block.timestamp); uint256 bonusReward = multiplier.mul(rewardPerTime); accTokenPerShare = accTokenPerShare.add(bonusReward.mul(PRECISION_FACTOR_MUL).div(stakedTokenSupply)); lastRewardTime = block.timestamp; } /** * @notice Burn percentage of tokens and return the remainder * @param _amount: Amount before burn * @return Amount after burn */ function _burnAndReturnStakedAmount(uint256 _amount) private returns(uint256) { // Calculate burn amount uint256 burnAmount = _amount.mul(feesController.candyFarmBurnPpm()).div(1000); // Burn IBurnable(address(stakedTokenPop)).burn(burnAmount); // Return amount after fees return _amount.sub(burnAmount); } /** * @notice Return reward multiplier over the given _from to _to time. * @param _from: time to start * @param _to: time to finish */ function _getMultiplier(uint256 _from, uint256 _to) internal view returns (uint256) { if (_to <= endDate) { return _to.sub(_from); } else if (_from >= endDate) { return 0; } else { return endDate.sub(_from); } } }
extend pool duration _newEndDate: new end date return Amount new reward tokens added to keep the same reward rate/
function _extendPoolInternal(uint256 _newEndDate) internal returns(uint256) { require(_newEndDate < block.timestamp + 60*60*24*365*10, "Candy farm must last less than 10 years!"); uint256 additionalRewardAmount = getAdditionalTokensRequiredToExtend(_newEndDate); endDate = _newEndDate; rewardTokenAmount = rewardTokenAmount.add(additionalRewardAmount); emit ExtendDuration(_newEndDate); emit RewardTokenAmountIncreased(rewardTokenAmount); return additionalRewardAmount; }
6,269,248
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___ _____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_ ___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_ __/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__ _\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____ _\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________ __\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________ ____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________ _______\/////////__\///_______\///__\///////////__\///____________*/ /** * @title CXIP ERC721 * @author CXIP-Labs * @notice A smart contract for minting and managing ERC721 NFTs. * @dev The entire logic and functionality of the smart contract is self-contained. */ contract CxipERC721 { /** * @dev Stores default collection data: name, symbol, and royalties. */ CollectionData private _collectionData; /** * @dev Internal last minted token id, to allow for auto-increment. */ uint256 private _currentTokenId; /** * @dev Array of all token ids in collection. */ uint256[] private _allTokens; /** * @dev Map of token id to array index of _ownedTokens. */ mapping(uint256 => uint256) private _ownedTokensIndex; /** * @dev Token id to wallet (owner) address map. */ mapping(uint256 => address) private _tokenOwner; /** * @dev 1-to-1 map of token id that was assigned an approved operator address. */ mapping(uint256 => address) private _tokenApprovals; /** * @dev Map of total tokens owner by a specific address. */ mapping(address => uint256) private _ownedTokensCount; /** * @dev Map of array of token ids owned by a specific address. */ mapping(address => uint256[]) private _ownedTokens; /** * @notice Map of full operator approval for a particular address. * @dev Usually utilised for supporting marketplace proxy wallets. */ mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Token data mapped by token id. */ mapping(uint256 => TokenData) private _tokenData; /** * @dev Address of admin user. Primarily used as an additional recover address. */ address private _admin; /** * @dev Address of contract owner. This address can run all onlyOwner functions. */ address private _owner; /** * @dev Simple tracker of all minted (not-burned) tokens. */ uint256 private _totalTokens; /** * @notice Event emitted when an token is minted, transfered, or burned. * @dev If from is empty, it's a mint. If to is empty, it's a burn. Otherwise, it's a transfer. * @param from Address from where token is being transfered. * @param to Address to where token is being transfered. * @param tokenId Token id that is being minted, Transfered, or burned. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @notice Event emitted when an address delegates power, for a token, to another address. * @dev Emits event that informs of address approving a third-party operator for a particular token. * @param wallet Address of the wallet configuring a token operator. * @param operator Address of the third-party operator approved for interaction. * @param tokenId A specific token id that is being authorised to operator. */ event Approval(address indexed wallet, address indexed operator, uint256 indexed tokenId); /** * @notice Event emitted when an address authorises an operator (third-party). * @dev Emits event that informs of address approving/denying a third-party operator. * @param wallet Address of the wallet configuring it's operator. * @param operator Address of the third-party operator that interacts on behalf of the wallet. * @param approved A boolean indicating whether approval was granted or revoked. */ event ApprovalForAll(address indexed wallet, address indexed operator, bool approved); /** * @notice Event emitted to signal to OpenSea that a permanent URI was created. * @dev Even though OpenSea advertises support for this, they do not listen to this event, and do not respond to it. * @param uri The permanent/static URL of the NFT. Cannot ever be changed again. * @param id Token id of the NFT. */ event PermanentURI(string uri, uint256 indexed id); /** * @notice Constructor is empty and not utilised. * @dev To make exact CREATE2 deployment possible, constructor is left empty. We utilize the "init" function instead. */ constructor() {} /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "CXIP: caller not an owner"); _; } /** * @notice Enables royaltiy functionality at the ERC721 level when ether is sent with no calldata. * @dev See implementation of _royaltiesFallback. */ receive() external payable { _royaltiesFallback(); } /** * @notice Enables royaltiy functionality at the ERC721 level no other function matches the call. * @dev See implementation of _royaltiesFallback. */ fallback() external { _royaltiesFallback(); } /** * @notice Gets the URI of the NFT on Arweave. * @dev Concatenates 2 sections of the arweave URI. * @param tokenId Id of the token. * @return string The URI. */ function arweaveURI(uint256 tokenId) external view returns (string memory) { return string(abi.encodePacked("https://arweave.net/", _tokenData[tokenId].arweave, _tokenData[tokenId].arweave2)); } /** * @notice Gets the URI of the NFT backup from CXIP. * @dev Concatenates to https://nft.cxip.io/. * @return string The URI. */ function contractURI() external view returns (string memory) { return string(abi.encodePacked("https://nft.cxip.io/", Strings.toHexString(address(this)), "/")); } /** * @notice Gets the creator's address. * @dev If the token Id doesn't exist it will return zero address. * @param tokenId Id of the token. * @return address Creator's address. */ function creator(uint256 tokenId) external view returns (address) { return _tokenData[tokenId].creator; } /** * @notice Gets the HTTP URI of the token. * @dev Concatenates to the baseURI. * @return string The URI. */ function httpURI(uint256 tokenId) external view returns (string memory) { return string(abi.encodePacked(baseURI(), "/", Strings.toHexString(tokenId))); } /** * @notice Gets the IPFS URI * @dev Concatenates to the IPFS domain. * @param tokenId Id of the token. * @return string The URI. */ function ipfsURI(uint256 tokenId) external view returns (string memory) { return string(abi.encodePacked("https://ipfs.io/ipfs/", _tokenData[tokenId].ipfs, _tokenData[tokenId].ipfs2)); } /** * @notice Gets the name of the collection. * @dev Uses two names to extend the max length of the collection name in bytes * @return string The collection name. */ function name() external view returns (string memory) { return string(abi.encodePacked(Bytes.trim(_collectionData.name), Bytes.trim(_collectionData.name2))); } /** * @notice Gets the hash of the NFT data used to create it. * @dev Payload is used for verification. * @param tokenId The Id of the token. * @return bytes32 The hash. */ function payloadHash(uint256 tokenId) external view returns (bytes32) { return _tokenData[tokenId].payloadHash; } /** * @notice Gets the signature of the signed NFT data used to create it. * @dev Used for signature verification. * @param tokenId The Id of the token. * @return Verification a struct containing v, r, s values of the signature. */ function payloadSignature(uint256 tokenId) external view returns (Verification memory) { return _tokenData[tokenId].payloadSignature; } /** * @notice Gets the address of the creator. * @dev The creator signs a payload while creating the NFT. * @param tokenId The Id of the token. * @return address The creator. */ function payloadSigner(uint256 tokenId) external view returns (address) { return _tokenData[tokenId].creator; } /** * @notice Shows the interfaces the contracts support * @dev Must add new 4 byte interface Ids here to acknowledge support * @param interfaceId ERC165 style 4 byte interfaceId. * @return bool True if supported. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { if ( interfaceId == 0x01ffc9a7 || // ERC165 interfaceId == 0x80ac58cd || // ERC721 // || interfaceId == 0x780e9d63 // ERC721Enumerable interfaceId == 0x5b5e139f || // ERC721Metadata interfaceId == 0x150b7a02 || // ERC721TokenReceiver interfaceId == 0xe8a3d485 || // contractURI() IPA1D(getRegistry().getPA1D()).supportsInterface(interfaceId) ) { return true; } else { return false; } } /** * @notice Gets the collection's symbol. * @dev Trims the symbol. * @return string The symbol. */ function symbol() external view returns (string memory) { return string(Bytes.trim(_collectionData.symbol)); } /** * @notice Get's the URI of the token. * @dev Defaults the the Arweave URI * @param tokenId The Id of the token. * @return string The URI. */ function tokenURI(uint256 tokenId) external view returns (string memory) { return string(abi.encodePacked("https://arweave.net/", _tokenData[tokenId].arweave, _tokenData[tokenId].arweave2)); } /** Disabled due to tokenEnumeration not enabled. * @notice Get list of tokens owned by wallet. * @param wallet The wallet address to get tokens for. * @return uint256[] Returns an array of token ids owned by wallet. function tokensOfOwner(address wallet) external view returns (uint256[] memory) { return _ownedTokens[wallet]; } */ /** * @notice Checks if a given hash matches a payload hash. * @dev Uses sha256 instead of keccak. * @param hash The hash to check. * @param payload The payload prehashed. * @return bool True if the hashes match. */ function verifySHA256(bytes32 hash, bytes calldata payload) external pure returns (bool) { bytes32 thePayloadHash = sha256(payload); return hash == thePayloadHash; } /** * @notice Adds a new address to the token's approval list. * @dev Requires the sender to be in the approved addresses. * @param to The address to approve. * @param tokenId The affected token. */ function approve(address to, uint256 tokenId) public { address tokenOwner = _tokenOwner[tokenId]; if (to != tokenOwner && _isApproved(msg.sender, tokenId)) { _tokenApprovals[tokenId] = to; emit Approval(tokenOwner, to, tokenId); } } /** * @notice Burns the token. * @dev The sender must be the owner or approved. * @param tokenId The token to burn. */ function burn(uint256 tokenId) public { if (_isApproved(msg.sender, tokenId)) { address wallet = _tokenOwner[tokenId]; require(!Address.isZero(wallet)); _clearApproval(tokenId); _tokenOwner[tokenId] = address(0); emit Transfer(wallet, address(0), tokenId); // _removeTokenFromOwnerEnumeration(wallet, tokenId); // uint256 index = _allTokens.length; // index--; // if (index == 0) { // delete _allTokens; // } else { // delete _allTokens[index]; // } _totalTokens -= 1; delete _tokenData[tokenId]; } } /** * @notice Initializes the collection. * @dev Special function to allow a one time initialisation on deployment. Also configures and deploys royalties. * @param newOwner The owner of the collection. * @param collectionData The collection data. */ function init(address newOwner, CollectionData calldata collectionData) public { require(Address.isZero(_admin), "CXIP: already initialized"); _admin = msg.sender; // temporary set to self, to pass rarible royalties logic trap _owner = address(this); _collectionData = collectionData; IPA1D(address(this)).init (0, payable(collectionData.royalties), collectionData.bps); // set to actual owner _owner = newOwner; } /** Disabled since this flow has not been agreed on. * @notice Transfer received NFTs to contract owner. * @dev Automatically transfer NFTs out of this smart contract to contract owner. This uses gas from sender. * @param _operator The smart contract where NFT is minted/operated. * @param _from The address from where NFT is being transfered from. * @param _tokenId NFT token id. * @param _data Arbitrary data that could be used for special function calls. * @return bytes4 Returns the onERC721Received interfaceId, to confirm successful receipt of NFT transfer. * function onERC721Received( address _operator, address /*_from*\/, uint256 _tokenId, bytes calldata _data ) public returns (bytes4) { ICxipERC721(_operator).safeTransferFrom( payable(address(this)), _owner, _tokenId, _data ); return 0x150b7a02; } */ /** * @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. * @param from cannot be the zero address. * @param to cannot be the zero address. * @param tokenId token must exist and be owned by `from`. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public payable { safeTransferFrom(from, to, tokenId, ""); } /** * @notice Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings. * are aware of the ERC721 protocol to prevent tokens from being forever locked. * @param from cannot be the zero address. * @param to cannot be the zero address. * @param tokenId token must exist and be owned by `from`. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory /*_data*/ ) public payable { if (_isApproved(msg.sender, tokenId)) { _transferFrom(from, to, tokenId); } } /** * @notice Adds a new approved operator. * @dev Allows platforms to sell/transfer all your NFTs. Used with proxy contracts like OpenSea/Rarible. * @param to The address to approve. * @param approved Turn on or off approval status. */ function setApprovalForAll(address to, bool approved) public { if (to != msg.sender) { _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } else { assert(false); } } /** * @notice Transfers `tokenId` token from `from` to `to`. * @dev WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * @param from cannot be the zero address. * @param to cannot be the zero address. * @param tokenId token must be owned by `from`. */ function transferFrom( address from, address to, uint256 tokenId ) public payable { transferFrom(from, to, tokenId, ""); } /** * @notice Transfers `tokenId` token from `from` to `to`. * @dev WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings. * @param from cannot be the zero address. * @param to cannot be the zero address. * @param tokenId token must be owned by `from`. */ function transferFrom( address from, address to, uint256 tokenId, bytes memory /*_data*/ ) public payable { if (_isApproved(msg.sender, tokenId)) { _transferFrom(from, to, tokenId); } } /** * @notice Mints and NFT. * @dev Includes event with the Arwave token URI. * @param id The new tokenId. * @param tokenData The token data for the NFT. * @return uint256 The new tokenId. */ function cxipMint(uint256 id, TokenData calldata tokenData) public onlyOwner returns (uint256) { if (id == 0) { _currentTokenId += 1; id = _currentTokenId; } _mint(tokenData.creator, id); _tokenData[id] = tokenData; emit PermanentURI(string(abi.encodePacked("https://arweave.net/", tokenData.arweave, tokenData.arweave2)), id); return id; } /** * @notice Sets a name for the collection. * @dev The name is split in two for gas optimization. * @param newName First part of name. * @param newName2 Second part of name. */ function setName(bytes32 newName, bytes32 newName2) public onlyOwner { _collectionData.name = newName; _collectionData.name2 = newName2; } /** * @notice Set a symbol for the collection. * @dev This is the ticker symbol for smart contract that shows up on EtherScan. * @param newSymbol The ticker symbol to set for smart contract. */ function setSymbol(bytes32 newSymbol) public onlyOwner { _collectionData.symbol = newSymbol; } /** * @notice Transfers ownership of the collection. * @dev Can't be the zero address. * @param newOwner Address of new owner. */ function transferOwnership(address newOwner) public onlyOwner { if (!Address.isZero(newOwner)) { _owner = newOwner; } } /** Disabled due to tokenEnumeration not enabled. * @notice Get total number of tokens owned by wallet. * @dev Used to see total amount of tokens owned by a specific wallet. * @param wallet Address for which to get token balance. * @return uint256 Returns an integer, representing total amount of tokens held by address. * function balanceOf(address wallet) public view returns (uint256) { return _ownedTokensCount[wallet]; } */ /** * @notice Get a base URI for the token. * @dev Concatenates with the CXIP domain name. * @return string the token URI. */ function baseURI() public view returns (string memory) { return string(abi.encodePacked("https://cxip.io/nft/", Strings.toHexString(address(this)))); } /** * @notice Gets the approved address for the token. * @dev Single operator set for a specific token. Usually used for one-time very specific authorisations. * @param tokenId Token id to get approved operator for. * @return address Approved address for token. */ function getApproved(uint256 tokenId) public view returns (address) { return _tokenApprovals[tokenId]; } /** * @notice Get the associated identity for the collection. * @dev Goes up the chain to read from the registry. * @return address Identity contract address. */ function getIdentity() public view returns (address) { return ICxipProvenance(getRegistry().getProvenance()).getWalletIdentity(_owner); } /** * @notice Checks if the address is approved. * @dev Includes references to OpenSea and Rarible marketplace proxies. * @param wallet Address of the wallet. * @param operator Address of the marketplace operator. * @return bool True if approved. */ function isApprovedForAll(address wallet, address operator) public view returns (bool) { return (_operatorApprovals[wallet][operator] || // Rarible Transfer Proxy 0x4feE7B061C97C9c496b01DbcE9CDb10c02f0a0Be == operator || // OpenSea Transfer Proxy address(OpenSeaProxyRegistry(0xa5409ec958C83C3f309868babACA7c86DCB077c1).proxies(wallet)) == operator); } /** * @notice Check if the sender is the owner. * @dev The owner could also be the admin or identity contract of the owner. * @return bool True if owner. */ function isOwner() public view returns (bool) { return (msg.sender == _owner || msg.sender == _admin || isIdentityWallet(msg.sender)); } /** * @notice Gets the owner's address. * @dev _owner is first set in init. * @return address Of ower. */ function owner() public view returns (address) { return _owner; } /** * @notice Checks who the owner of a token is. * @dev The token must exist. * @param tokenId The token to look up. * @return address Owner of the token. */ function ownerOf(uint256 tokenId) public view returns (address) { address tokenOwner = _tokenOwner[tokenId]; require(!Address.isZero(tokenOwner), "ERC721: token does not exist"); return tokenOwner; } /** Disabled due to tokenEnumeration not enabled. * @notice Get token by index instead of token id. * @dev Helpful for token enumeration where token id info is not yet available. * @param index Index of token in array. * @return uint256 Returns the token id of token located at that index. function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply()); return _allTokens[index]; } */ /** Disabled due to tokenEnumeration not enabled. * @notice Get token from wallet by index instead of token id. * @dev Helpful for wallet token enumeration where token id info is not yet available. Use in conjunction with balanceOf function. * @param wallet Specific address for which to get token for. * @param index Index of token in array. * @return uint256 Returns the token id of token located at that index in specified wallet. * function tokenOfOwnerByIndex( address wallet, uint256 index ) public view returns (uint256) { require(index < balanceOf(wallet)); return _ownedTokens[wallet][index]; } */ /** Disabled due to tokenEnumeration not enabled. * @notice Total amount of tokens in the collection. * @dev Ignores burned tokens. * @return uint256 Returns the total number of active (not burned) tokens. * function totalSupply() public view returns (uint256) { return _allTokens.length; } */ /** * @notice Total amount of tokens in the collection. * @dev Ignores burned tokens. * @return uint256 Returns the total number of active (not burned) tokens. */ function totalSupply() public view returns (uint256) { return _totalTokens; } /** * @notice Empty function that is triggered by external contract on NFT transfer. * @dev We have this blank function in place to make sure that external contract sending in NFTs don't error out. * @dev Since it's not being used, the _operator variable is commented out to avoid compiler warnings. * @dev Since it's not being used, the _from variable is commented out to avoid compiler warnings. * @dev Since it's not being used, the _tokenId variable is commented out to avoid compiler warnings. * @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings. * @return bytes4 Returns the interfaceId of onERC721Received. */ function onERC721Received( address, /*_operator*/ address, /*_from*/ uint256, /*_tokenId*/ bytes calldata /*_data*/ ) public pure returns (bytes4) { return 0x150b7a02; } /** * @notice Allows retrieval of royalties from the contract. * @dev This is a default fallback to ensure the royalties are available. */ function _royaltiesFallback() internal { address _target = getRegistry().getPA1D(); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), _target, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @notice Checks if an address is an identity contract. * @dev It must also be registred. * @param sender Address to check if registered to identity. * @return bool True if registred identity. */ function isIdentityWallet(address sender) internal view returns (bool) { address identity = getIdentity(); if (Address.isZero(identity)) { return false; } return ICxipIdentity(identity).isWalletRegistered(sender); } /** * @dev Get the top-level CXIP Registry smart contract. Function must always be internal to prevent miss-use/abuse through bad programming practices. * @return ICxipRegistry The address of the top-level CXIP Registry smart contract. */ function getRegistry() internal pure returns (ICxipRegistry) { return ICxipRegistry(0xC267d41f81308D7773ecB3BDd863a902ACC01Ade); } /** Disabled due to tokenEnumeration not enabled. * @dev Add a newly minted token into managed list of tokens. * @param to Address of token owner for which to add the token. * @param tokenId Id of token to add. function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokensCount[to]; _ownedTokensCount[to]++; _ownedTokens[to].push(tokenId); } */ /** * @notice Deletes a token from the approval list. * @dev Removes from count. * @param tokenId T. */ function _clearApproval(uint256 tokenId) private { delete _tokenApprovals[tokenId]; } /** * @notice Mints an NFT. * @dev Can to mint the token to the zero address and the token cannot already exist. * @param to Address to mint to. * @param tokenId The new token. */ function _mint(address to, uint256 tokenId) private { if (Address.isZero(to) || _exists(tokenId)) { assert(false); } _tokenOwner[tokenId] = to; emit Transfer(address(0), to, tokenId); // _addTokenToOwnerEnumeration(to, tokenId); _totalTokens += 1; // _allTokens.push(tokenId); } /** Disabled due to tokenEnumeration not enabled. * @dev Remove a token from managed list of tokens. * @param from Address of token owner for which to remove the token. * @param tokenId Id of token to remove. function _removeTokenFromOwnerEnumeration( address from, uint256 tokenId ) private { _ownedTokensCount[from]--; uint256 lastTokenIndex = _ownedTokensCount[from]; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if(tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; _ownedTokensIndex[lastTokenId] = tokenIndex; } if(lastTokenIndex == 0) { delete _ownedTokens[from]; } else { delete _ownedTokens[from][lastTokenIndex]; } } */ /** * @dev Primary internal function that handles the transfer/mint/burn functionality. * @param from Address from where token is being transferred. Zero address means it is being minted. * @param to Address to whom the token is being transferred. Zero address means it is being burned. * @param tokenId Id of token that is being transferred/minted/burned. */ function _transferFrom( address from, address to, uint256 tokenId ) private { if (_tokenOwner[tokenId] == from && !Address.isZero(to)) { _clearApproval(tokenId); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); // _removeTokenFromOwnerEnumeration(from, tokenId); // _addTokenToOwnerEnumeration(to, tokenId); } else { assert(false); } } /** * @notice Checks if the token owner exists. * @dev If the address is the zero address no owner exists. * @param tokenId The affected token. * @return bool True if it exists. */ function _exists(uint256 tokenId) private view returns (bool) { address tokenOwner = _tokenOwner[tokenId]; return !Address.isZero(tokenOwner); } /** * @notice Checks if the address is an approved one. * @dev Uses inlined checks for different usecases of approval. * @param spender Address of the spender. * @param tokenId The affected token. * @return bool True if approved. */ function _isApproved(address spender, uint256 tokenId) private view returns (bool) { require(_exists(tokenId)); address tokenOwner = _tokenOwner[tokenId]; return ( spender == tokenOwner || getApproved(tokenId) == spender || isApprovedForAll(tokenOwner, spender) ); } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } function isZero(address account) internal pure returns (bool) { return (account == address(0)); } } library Bytes { function getBoolean(uint192 _packedBools, uint192 _boolNumber) internal pure returns (bool) { uint192 flag = (_packedBools >> _boolNumber) & uint192(1); return (flag == 1 ? true : false); } function setBoolean( uint192 _packedBools, uint192 _boolNumber, bool _value ) internal pure returns (uint192) { if (_value) { return _packedBools | (uint192(1) << _boolNumber); } else { return _packedBools & ~(uint192(1) << _boolNumber); } } function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { tempBytes := mload(0x40) let lengthmod := and(_length, 31) let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) mstore(0x40, and(add(mc, 31), not(31))) } default { tempBytes := mload(0x40) mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function trim(bytes32 source) internal pure returns (bytes memory) { uint256 temp = uint256(source); uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return slice(abi.encodePacked(source), 32 - length, length); } } struct CollectionData { bytes32 name; bytes32 name2; bytes32 symbol; address royalties; uint96 bps; } interface ICxipERC721 { function arweaveURI(uint256 tokenId) external view returns (string memory); function contractURI() external view returns (string memory); function creator(uint256 tokenId) external view returns (address); function httpURI(uint256 tokenId) external view returns (string memory); function ipfsURI(uint256 tokenId) external view returns (string memory); function name() external view returns (string memory); function payloadHash(uint256 tokenId) external view returns (bytes32); function payloadSignature(uint256 tokenId) external view returns (Verification memory); function payloadSigner(uint256 tokenId) external view returns (address); function supportsInterface(bytes4 interfaceId) external view returns (bool); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); /* Disabled due to tokenEnumeration not enabled. function tokensOfOwner( address wallet ) external view returns (uint256[] memory); */ function verifySHA256(bytes32 hash, bytes calldata payload) external pure returns (bool); function approve(address to, uint256 tokenId) external; function burn(uint256 tokenId) external; function init(address newOwner, CollectionData calldata collectionData) external; /* Disabled since this flow has not been agreed on. function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); */ function safeTransferFrom( address from, address to, uint256 tokenId ) external payable; function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) external payable; function setApprovalForAll(address to, bool approved) external; function transferFrom( address from, address to, uint256 tokenId ) external payable; function transferFrom( address from, address to, uint256 tokenId, bytes memory data ) external payable; function cxipMint(uint256 id, TokenData calldata tokenData) external returns (uint256); function setApprovalForAll( address from, address to, bool approved ) external; function setName(bytes32 newName, bytes32 newName2) external; function setSymbol(bytes32 newSymbol) external; function transferOwnership(address newOwner) external; /* // Disabled due to tokenEnumeration not enabled. function balanceOf(address wallet) external view returns (uint256); */ function baseURI() external view returns (string memory); function getApproved(uint256 tokenId) external view returns (address); function getIdentity() external view returns (address); function isApprovedForAll(address wallet, address operator) external view returns (bool); function isOwner() external view returns (bool); function owner() external view returns (address); function ownerOf(uint256 tokenId) external view returns (address); /* Disabled due to tokenEnumeration not enabled. function tokenByIndex(uint256 index) external view returns (uint256); */ /* Disabled due to tokenEnumeration not enabled. function tokenOfOwnerByIndex( address wallet, uint256 index ) external view returns (uint256); */ /* Disabled due to tokenEnumeration not enabled. function totalSupply() external view returns (uint256); */ function totalSupply() external view returns (uint256); function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external pure returns (bytes4); } interface ICxipIdentity { function addSignedWallet( address newWallet, uint8 v, bytes32 r, bytes32 s ) external; function addWallet(address newWallet) external; function connectWallet() external; function createERC721Token( address collection, uint256 id, TokenData calldata tokenData, Verification calldata verification ) external returns (uint256); function createERC721Collection( bytes32 saltHash, address collectionCreator, Verification calldata verification, CollectionData calldata collectionData ) external returns (address); function createCustomERC721Collection( bytes32 saltHash, address collectionCreator, Verification calldata verification, CollectionData calldata collectionData, bytes32 slot, bytes memory bytecode ) external returns (address); function init(address wallet, address secondaryWallet) external; function getAuthorizer(address wallet) external view returns (address); function getCollectionById(uint256 index) external view returns (address); function getCollectionType(address collection) external view returns (InterfaceType); function getWallets() external view returns (address[] memory); function isCollectionCertified(address collection) external view returns (bool); function isCollectionRegistered(address collection) external view returns (bool); function isNew() external view returns (bool); function isOwner() external view returns (bool); function isTokenCertified(address collection, uint256 tokenId) external view returns (bool); function isTokenRegistered(address collection, uint256 tokenId) external view returns (bool); function isWalletRegistered(address wallet) external view returns (bool); function listCollections(uint256 offset, uint256 length) external view returns (address[] memory); function nextNonce(address wallet) external view returns (uint256); function totalCollections() external view returns (uint256); function isCollectionOpen(address collection) external pure returns (bool); } interface ICxipProvenance { function createIdentity( bytes32 saltHash, address wallet, uint8 v, bytes32 r, bytes32 s ) external returns (uint256, address); function createIdentityBatch( bytes32 saltHash, address[] memory wallets, uint8[] memory V, bytes32[] memory RS ) external returns (uint256, address); function getIdentity() external view returns (address); function getWalletIdentity(address wallet) external view returns (address); function informAboutNewWallet(address newWallet) external; function isIdentityValid(address identity) external view returns (bool); function nextNonce(address wallet) external view returns (uint256); } interface ICxipRegistry { function getAsset() external view returns (address); function getAssetSigner() external view returns (address); function getAssetSource() external view returns (address); function getCopyright() external view returns (address); function getCopyrightSource() external view returns (address); function getCustomSource(bytes32 name) external view returns (address); function getCustomSourceFromString(string memory name) external view returns (address); function getERC1155CollectionSource() external view returns (address); function getERC721CollectionSource() external view returns (address); function getIdentitySource() external view returns (address); function getPA1D() external view returns (address); function getPA1DSource() external view returns (address); function getProvenance() external view returns (address); function getProvenanceSource() external view returns (address); function owner() external view returns (address); function setAsset(address proxy) external; function setAssetSigner(address source) external; function setAssetSource(address source) external; function setCopyright(address proxy) external; function setCopyrightSource(address source) external; function setCustomSource(string memory name, address source) external; function setERC1155CollectionSource(address source) external; function setERC721CollectionSource(address source) external; function setIdentitySource(address source) external; function setPA1D(address proxy) external; function setPA1DSource(address source) external; function setProvenance(address proxy) external; function setProvenanceSource(address source) external; } // This is a 256 value limit (uint8) enum InterfaceType { NULL, // 0 ERC20, // 1 ERC721, // 2 ERC1155 // 3 } interface IPA1D { function init( uint256 tokenId, address payable receiver, uint256 bp ) external; function configurePayouts(address payable[] memory addresses, uint256[] memory bps) external; function getPayoutInfo() external view returns (address payable[] memory addresses, uint256[] memory bps); function getEthPayout() external; function getTokenPayout(address tokenAddress) external; function getTokenPayoutByName(string memory tokenName) external; function getTokensPayout(address[] memory tokenAddresses) external; function getTokensPayoutByName(string[] memory tokenNames) external; function supportsInterface(bytes4 interfaceId) external pure returns (bool); function setRoyalties( uint256 tokenId, address payable receiver, uint256 bp ) external; function royaltyInfo(uint256 tokenId, uint256 value) external view returns (address, uint256); function getFeeBps(uint256 tokenId) external view returns (uint256[] memory); function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function tokenCreator(address contractAddress, uint256 tokenId) external view returns (address); function calculateRoyaltyFee( address contractAddress, uint256 tokenId, uint256 amount ) external view returns (uint256); function marketContract() external view returns (address); function tokenCreators(uint256 tokenId) external view returns (address); function bidSharesForToken(uint256 tokenId) external view returns (Zora.BidShares memory bidShares); function getStorageSlot(string calldata slot) external pure returns (bytes32); function getTokenAddress(string memory tokenName) external view returns (address); } contract OpenSeaOwnableDelegateProxy {} contract OpenSeaProxyRegistry { mapping(address => OpenSeaOwnableDelegateProxy) public proxies; } library Strings { function toHexString(address account) internal pure returns (string memory) { return toHexString(uint256(uint160(account))); } 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); } 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] = bytes16("0123456789abcdef")[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } struct Token { address collection; uint256 tokenId; InterfaceType tokenType; address creator; } struct TokenData { bytes32 payloadHash; Verification payloadSignature; address creator; bytes32 arweave; bytes11 arweave2; bytes32 ipfs; bytes14 ipfs2; } // This is a 256 value limit (uint8) enum UriType { ARWEAVE, // 0 IPFS, // 1 HTTP // 2 } struct Verification { bytes32 r; bytes32 s; uint8 v; } library Zora { struct Decimal { uint256 value; } struct BidShares { // % of sale value that goes to the _previous_ owner of the nft Decimal prevOwner; // % of sale value that goes to the original creator of the nft Decimal creator; // % of sale value that goes to the seller (current owner) of the nft Decimal owner; } }
Get's the URI of the token. Defaults the the Arweave URI tokenId The Id of the token. return string The URI./
function tokenURI(uint256 tokenId) external view returns (string memory) { return }
411,404
//SPDX-License-Identifier: UNLICENSED pragma solidity ^0.5.0; import "./ERC1155Tradable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier * available, which can be aplied 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. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor() internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require( localCounter == _guardCounter, "ReentrancyGuard: reentrant call" ); } } 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 { // 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 ); 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. // 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).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" ); } } } // 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); } // Inheritance // https://docs.synthetix.io/contracts/RewardsDistributionRecipient contract RewardsDistributionRecipient is Owned { address public rewardsDistribution; function notifyRewardAmount( uint256 rewardNotifyAmount, uint256 rewardTransferAmount ) external; modifier onlyRewardsDistribution() { require(msg.sender == rewardsDistribution, "Wrong caller"); _; } function setRewardsDistribution(address _rewardsDistribution) external onlyOwner { rewardsDistribution = _rewardsDistribution; } } contract TokenWrapper is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public stakingToken; uint256 private _totalSupply; mapping(address => uint256) private _balances; constructor(address _stakingToken) public { stakingToken = IERC20(_stakingToken); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public nonReentrant { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public nonReentrant { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); } } interface IStratAccessNft { function getTotalUseCount(address _account, uint256 _id) external view returns (uint256); function getStratUseCount( address _account, uint256 _id, address _strategy ) external view returns (uint256); function startUsingNFT(address _account, uint256 _id) external; function endUsingNFT(address _account, uint256 _id) external; } contract DarkParadise is TokenWrapper, RewardsDistributionRecipient { IERC20 public rewardsToken; uint256 public DURATION = 1 seconds; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; //NFT IStratAccessNft public nft; // common, rare, unique ids considered in range on 1-111 uint256 public constant rareMinId = 101; uint256 public constant uniqueId = 111; uint256 public minNFTId = 223; uint256 public maxNFTId = 444; uint256 public commonLimit = 3200 * 10**18; uint256 public rareLimit = 16500 * 10**18; uint256 public uniqueLimit = 30000 * 10**18; mapping(address => uint256) public usedNFT; event RewardAdded(uint256 rewardNotifyAmount, uint256 rewardTransferAmount); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event DurationChange(uint256 newDuration, uint256 oldDuration); event NFTSet(IStratAccessNft indexed newNFT); constructor( address _owner, address _rewardsToken, address _stakingToken, IStratAccessNft _nft ) public TokenWrapper(_stakingToken) Owned(_owner) { rewardsToken = IERC20(_rewardsToken); nft = _nft; } modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getLimit(address user) public view returns (uint256) { uint256 nftId = usedNFT[user]; if (nftId == 0) return 0; uint256 effectiveId = ((nftId - 1) % 111) + 1; if (effectiveId < rareMinId) return commonLimit; if (effectiveId < uniqueId) return rareLimit; return uniqueLimit; } function setNFT(IStratAccessNft _nftAddress) public onlyOwner { nft = _nftAddress; emit NFTSet(_nftAddress); } function setDepositLimits( uint256 _common, uint256 _rare, uint256 _unique ) external onlyOwner { if (commonLimit != _common) commonLimit = _common; if (rareLimit != _rare) rareLimit = _rare; if (uniqueLimit != _unique) uniqueLimit = _unique; } function setMinMaxNFT(uint256 _min, uint256 _max) external onlyOwner { if (minNFTId != _min) minNFTId = _min; if (maxNFTId != _max) maxNFTId = _max; } function setDuration(uint256 newDuration) external onlyOwner { emit DurationChange(newDuration, DURATION); DURATION = newDuration; } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount, uint256 _nftId) public updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); require(_nftId >= minNFTId && _nftId <= maxNFTId, "Invalid nft"); if (usedNFT[msg.sender] == 0) { usedNFT[msg.sender] = _nftId; nft.startUsingNFT(msg.sender, _nftId); } require( (amount + balanceOf(msg.sender)) <= getLimit(msg.sender), "Crossing limit" ); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); //When a user withdraws their entire SDT from the strat, the strat stops using their NFT if (balanceOf(msg.sender) - amount == 0) { uint256 nftId = usedNFT[msg.sender]; usedNFT[msg.sender] = 0; nft.endUsingNFT(msg.sender, nftId); } super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function notifyRewardAmount( uint256 rewardNotifyAmount, uint256 rewardTransferAmount ) external onlyRewardsDistribution updateReward(address(0)) { require(rewardNotifyAmount >= rewardTransferAmount, "!Notify Amount"); if (block.timestamp >= periodFinish) { rewardRate = rewardNotifyAmount.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = rewardNotifyAmount.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); rewardsToken.safeTransferFrom( msg.sender, address(this), rewardTransferAmount ); emit RewardAdded(rewardNotifyAmount, rewardTransferAmount); } } //SPDX-License-Identifier: UNLICENSED pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.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]; } } contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor() internal { _addMinter(_msgSender()); } modifier onlyMinter() { require( isMinter(_msgSender()), "MinterRole: caller does not have the Minter role" ); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole is Context { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor() internal { _addWhitelistAdmin(_msgSender()); } modifier onlyWhitelistAdmin() { require( isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role" ); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(_msgSender()); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas * @param _interfaceId The interface identifier, as specified in ERC-165 */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } /** * @dev ERC-1155 interface for accepting safe transfers. */ interface IERC1155TokenReceiver { /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount 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 _amount, bytes calldata _data ) external returns (bytes4); /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived( address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data ) external returns (bytes4); /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more than 5,000 gas. * @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported. */ function supportsInterface(bytes4 interfaceID) external view returns (bool); } interface IERC1155 { // Events /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferSingle( address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount ); /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferBatch( address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts ); /** * @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 _amount, uint256 indexed _id); /** * @notice Transfers 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 `_amount` 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 amount 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 _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data ) external; /** * @notice Send multiple types of Tokens from the _from address to the _to address (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 `_amounts` * MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` 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 amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts 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 _amounts, bytes calldata _data ) external; /** * @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 The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); /** * @notice Enable or disable approval for a third party ("operator") to manage all of 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 isOperator); } /** * @dev Implementation of Multi-Token Standard contract */ contract ERC1155 is IERC165 { using SafeMath for uint256; using Address for address; /***********************************| | Variables and Events | |__________________________________*/ // onReceive function signatures bytes4 internal constant ERC1155_RECEIVED_VALUE = 0xf23a6e61; bytes4 internal constant ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81; // Objects balances mapping(address => mapping(uint256 => uint256)) internal balances; // Operator Functions mapping(address => mapping(address => bool)) internal operators; // Events event TransferSingle( address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount ); event TransferBatch( address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); event URI(string _uri, uint256 indexed _id); /***********************************| | Public Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data ) public { require( (msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeTransferFrom: INVALID_OPERATOR" ); require( _to != address(0), "ERC1155#safeTransferFrom: INVALID_RECIPIENT" ); // require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations _safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, _data); } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts 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[] memory _ids, uint256[] memory _amounts, bytes memory _data ) public { // Requirements require( (msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR" ); require( _to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT" ); _safeBatchTransferFrom(_from, _to, _ids, _amounts); _callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data); } /***********************************| | Internal Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount */ function _safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount ) internal { // Update balances balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount // Emit event emit TransferSingle(msg.sender, _from, _to, _id, _amount); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...) */ function _callonERC1155Received( address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data ) internal { // Check if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received( msg.sender, _from, _id, _amount, _data ); require( retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE" ); } } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type */ function _safeBatchTransferFrom( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts ) internal { require( _ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH" ); // Number of transfer to execute uint256 nTransfer = _ids.length; // Executing all transfers for (uint256 i = 0; i < nTransfer; i++) { // Update storage balance of previous bin balances[_from][_ids[i]] = balances[_from][_ids[i]].sub( _amounts[i] ); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit event emit TransferBatch(msg.sender, _from, _to, _ids, _amounts); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...) */ function _callonERC1155BatchReceived( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) internal { // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived( msg.sender, _from, _ids, _amounts, _data ); require( retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE" ); } } /***********************************| | Operator Functions | |__________________________________*/ /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @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 { // Update operator status operators[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 view returns (bool isOperator) { return operators[_owner][_operator]; } /***********************************| | Balance Functions | |__________________________________*/ /** * @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) public view returns (uint256) { return balances[_owner][_id]; } /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] memory _owners, uint256[] memory _ids) public view returns (uint256[] memory) { require( _owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH" ); // Variables uint256[] memory batchBalances = new uint256[](_owners.length); // Iterate over each owner and token ID for (uint256 i = 0; i < _owners.length; i++) { batchBalances[i] = balances[_owners[i]][_ids[i]]; } return batchBalances; } /***********************************| | ERC165 Functions | |__________________________________*/ /** * INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); */ bytes4 private constant INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; /** * INTERFACE_SIGNATURE_ERC1155 = * bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^ * bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^ * bytes4(keccak256("balanceOf(address,uint256)")) ^ * bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^ * bytes4(keccak256("setApprovalForAll(address,bool)")) ^ * bytes4(keccak256("isApprovedForAll(address,address)")); */ bytes4 private constant INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; /** * @notice 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 */ function supportsInterface(bytes4 _interfaceID) external view returns (bool) { if ( _interfaceID == INTERFACE_SIGNATURE_ERC165 || _interfaceID == INTERFACE_SIGNATURE_ERC1155 ) { return true; } return false; } } /** * @notice Contract that handles metadata related methods. * @dev Methods assume a deterministic generation of URI based on token IDs. * Methods also assume that URI uses hex representation of token IDs. */ contract ERC1155Metadata { // URI's default URI prefix string internal baseMetadataURI; event URI(string _uri, uint256 indexed _id); /***********************************| | Metadata Public Function s | |__________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * Token IDs are assumed to be represented in their hex format in URIs * @return URI string */ function uri(uint256 _id) public view returns (string memory) { return string(abi.encodePacked(baseMetadataURI, _uint2str(_id), ".json")); } /***********************************| | Metadata Internal Functions | |__________________________________*/ /** * @notice Will emit default URI log event for corresponding token _id * @param _tokenIDs Array of IDs of tokens to log default URI */ function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseMetadataURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string( abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json") ); emit URI(tokenURI, _tokenIDs[i]); } } /** * @notice Will emit a specific URI log event for corresponding token * @param _tokenIDs IDs of the token corresponding to the _uris logged * @param _URIs The URIs of the specified _tokenIDs */ function _logURIs(uint256[] memory _tokenIDs, string[] memory _URIs) internal { require( _tokenIDs.length == _URIs.length, "ERC1155Metadata#_logURIs: INVALID_ARRAYS_LENGTH" ); for (uint256 i = 0; i < _tokenIDs.length; i++) { emit URI(_URIs[i], _tokenIDs[i]); } } /** * @notice Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal { baseMetadataURI = _newBaseMetadataURI; } /***********************************| | Utility Internal Functions | |__________________________________*/ /** * @notice Convert uint256 to string * @param _i Unsigned integer to convert to string */ function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; // Get number of bytes while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; // Get each individual ASCII while (ii != 0) { bstr[k--] = bytes1(uint8(48 + (ii % 10))); ii /= 10; } // Convert to string return string(bstr); } } /** * @dev Multi-Fungible Tokens with minting and burning methods. These methods assume * a parent contract to be executed as they are `internal` functions */ contract ERC1155MintBurn is ERC1155 { /****************************************| | Minting Functions | |_______________________________________*/ /** * @notice Mint _amount of tokens of a given id * @param _to The address to mint tokens to * @param _id Token id to mint * @param _amount The amount to be minted * @param _data Data to pass if receiver is contract */ function _mint( address _to, uint256 _id, uint256 _amount, bytes memory _data ) internal { // Add _amount balances[_to][_id] = balances[_to][_id].add(_amount); // Emit event emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount); // Calling onReceive method if recipient is contract _callonERC1155Received(address(0x0), _to, _id, _amount, _data); } /** * @notice Mint tokens for each ids in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Data to pass if receiver is contract */ function _batchMint( address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) internal { require( _ids.length == _amounts.length, "ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH" ); // Number of mints to execute uint256 nMint = _ids.length; // Executing all minting for (uint256 i = 0; i < nMint; i++) { // Update storage balance balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts); // Calling onReceive method if recipient is contract _callonERC1155BatchReceived(address(0x0), _to, _ids, _amounts, _data); } /****************************************| | Burning Functions | |_______________________________________*/ /** * @notice Burn _amount of tokens of a given token id * @param _from The address to burn tokens from * @param _id Token id to burn * @param _amount The amount to be burned */ function _burn( address _from, uint256 _id, uint256 _amount ) internal { //Substract _amount balances[_from][_id] = balances[_from][_id].sub(_amount); // Emit event emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount); } /** * @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _amounts Array of the amount to be burned */ function _batchBurn( address _from, uint256[] memory _ids, uint256[] memory _amounts ) internal { require( _ids.length == _amounts.length, "ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH" ); // Number of mints to execute uint256 nBurn = _ids.length; // Executing all minting for (uint256 i = 0; i < nBurn; i++) { // Update storage balance balances[_from][_ids[i]] = balances[_from][_ids[i]].sub( _amounts[i] ); } // Emit batch mint event emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts); } } library Strings { // 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); uint256 k = 0; for (uint256 i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint256 i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint256 i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint256 i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint256 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(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC1155Tradable * ERC1155Tradable - ERC1155 contract that whitelists an operator address, * has create and mint functionality, and supports useful standards from OpenZeppelin, like _exists(), name(), symbol(), and totalSupply() */ contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable, MinterRole, WhitelistAdminRole { using Strings for string; address proxyRegistryAddress; uint256 internal _currentTokenID = 0; mapping(uint256 => address) public creators; mapping(uint256 => uint256) public tokenSupply; mapping(uint256 => uint256) public tokenMaxSupply; // Contract name string public name; // Contract symbol string public symbol; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) public { name = _name; symbol = _symbol; proxyRegistryAddress = _proxyRegistryAddress; } function removeWhitelistAdmin(address account) public onlyOwner { _removeWhitelistAdmin(account); } function removeMinter(address account) public onlyOwner { _removeMinter(account); } function uri(uint256 _id) public view returns (string memory) { require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return Strings.strConcat(baseMetadataURI, Strings.uint2str(_id)); } /** * @dev Returns the total quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function totalSupply(uint256 _id) public view returns (uint256) { return tokenSupply[_id]; } /** * @dev Returns the max quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function maxSupply(uint256 _id) public view returns (uint256) { return tokenMaxSupply[_id]; } /** * @dev Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function setBaseMetadataURI(string memory _newBaseMetadataURI) public onlyWhitelistAdmin { _setBaseMetadataURI(_newBaseMetadataURI); } /** * @dev Creates a new token type and assigns _initialSupply to an address * @param _maxSupply max supply allowed * @param _initialSupply Optional amount to supply the first owner * @param _uri Optional URI for this token type * @param _data Optional data to pass if receiver is contract * @return The newly created token ID */ function create( uint256 _maxSupply, uint256 _initialSupply, string memory _uri, bytes memory _data ) public onlyWhitelistAdmin returns (uint256 tokenId) { require(_initialSupply <= _maxSupply, "_initialSupply > _maxSupply"); uint256 _id = _getNextTokenID(); _incrementTokenTypeId(); creators[_id] = msg.sender; if (bytes(_uri).length > 0) { emit URI(_uri, _id); } if (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data); tokenSupply[_id] = _initialSupply; tokenMaxSupply[_id] = _maxSupply; return _id; } /** * @dev Creates multiple new token types and assigns _initialSupply[i] of each token type, to an address * @param _maxSupply Array of max supplies allowed * @param _initialSupply Array of optional amounts to supply the first owner * @param _uri Array of optional URIs for each token type * @param _data Optional data to pass if receiver is contract. Same for each new token type * @return Array of newly created token IDs */ function batchCreate( uint256[] calldata _maxSupply, uint256[] calldata _initialSupply, string[] calldata _uri, bytes calldata _data ) external onlyWhitelistAdmin returns (uint256[] memory) { require( _initialSupply.length == _maxSupply.length && _uri.length == _maxSupply.length, "Array lengths mismatch" ); uint256[] memory _ids = new uint256[](_maxSupply.length); uint256 _id = 0; for (uint256 index = 0; index < _maxSupply.length; index++) { _id = create( _maxSupply[index], _initialSupply[index], _uri[index], _data ); _ids[index] = _id; } return _ids; } /** * @dev Mints some amount of tokens to an address * @param _to Address of the future owner of the token * @param _id Token ID to mint * @param _quantity Amount of tokens to mint * @param _data Data to pass if receiver is contract */ function mint( address _to, uint256 _id, uint256 _quantity, bytes memory _data ) public onlyMinter { uint256 tokenId = _id; require( tokenSupply[tokenId] < tokenMaxSupply[tokenId], "Max supply reached" ); _mint(_to, _id, _quantity, _data); tokenSupply[_id] = tokenSupply[_id].add(_quantity); } /** * @dev Mints some amount of tokens to an address * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Data to pass if receiver is contract */ function batchMint( address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) public onlyMinter { uint256 nMints = _ids.length; for (uint256 i = 0; i < nMints; i++) { uint256 tokenId = _ids[i]; require( tokenSupply[tokenId] < tokenMaxSupply[tokenId], "Max supply reached" ); tokenSupply[tokenId] = tokenSupply[tokenId].add(_amounts[i]); } _batchMint(_to, _ids, _amounts, _data); } /** * @notice Burn _amount of tokens of a given token id * @param _from The address to burn tokens from * @param _id Token id to burn * @param _amount The amount to be burned */ function burn( address _from, uint256 _id, uint256 _amount ) public onlyOwner { tokenSupply[_id] = tokenSupply[_id].sub(_amount); _burn(_from, _id, _amount); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings. */ function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** * @dev Returns whether the specified token exists by checking to see if it has a creator * @param _id uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 _id) internal view returns (bool) { return creators[_id] != address(0); } /** * @dev calculates the next token ID based on value of _currentTokenID * @return uint256 for the next token ID */ function _getNextTokenID() private view returns (uint256) { return _currentTokenID.add(1); } /** * @dev increments the value of _currentTokenID */ function _incrementTokenTypeId() private { _currentTokenID++; } } pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } 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; } } pragma solidity ^0.5.0; import "../GSN/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. * * 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(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } 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); } pragma solidity ^0.5.5; /** * @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 Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ 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"); } }
stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount, uint256 _nftId) public updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); require(_nftId >= minNFTId && _nftId <= maxNFTId, "Invalid nft"); if (usedNFT[msg.sender] == 0) { usedNFT[msg.sender] = _nftId; nft.startUsingNFT(msg.sender, _nftId); } require( (amount + balanceOf(msg.sender)) <= getLimit(msg.sender), "Crossing limit" ); super.stake(amount); emit Staked(msg.sender, amount); }
5,823,644
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; interface IERC677Receiver { function onTokenTransfer(address _sender, uint _value, bytes calldata _data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; interface ISideToken { function mint(address account, uint256 amount, bytes calldata userData, bytes calldata operatorData) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; interface ISideTokenFactory { function createSideToken(string calldata name, string calldata symbol, uint256 granularity) external returns(address); event SideTokenCreated(address indexed sideToken, string symbol, uint256 granularity); } //SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; // https://github.com/0xProject/0x-monorepo/blob/development/contracts/utils/contracts/src/LibEIP712.sol library LibEIP712 { // Hash of the EIP712 Domain Separator Schema // keccak256(abi.encodePacked( // "EIP712Domain(", // "string name,", // "string version,", // "uint256 chainId,", // "address verifyingContract", // ")" // )) bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev Calculates a EIP712 domain separator. /// @param name The EIP712 domain name. /// @param version The EIP712 domain version. /// @param verifyingContract The EIP712 verifying contract. /// @return result EIP712 domain separator. function hashEIP712Domain( string memory name, string memory version, uint256 chainId, address verifyingContract ) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, // keccak256(bytes(name)), // keccak256(bytes(version)), // chainId, // uint256(verifyingContract) // )) // solium-disable-next-line security/no-inline-assembly assembly { // Calculate hashes of dynamic data let nameHash := keccak256(add(name, 32), mload(name)) let versionHash := keccak256(add(version, 32), mload(version)) // Load free memory pointer let memPtr := mload(64) // Store params in memory mstore(memPtr, schemaHash) mstore(add(memPtr, 32), nameHash) mstore(add(memPtr, 64), versionHash) mstore(add(memPtr, 96), chainId) mstore(add(memPtr, 128), verifyingContract) // Compute hash result := keccak256(memPtr, 160) } return result; } /// @dev Calculates EIP712 encoding for a hash struct with a given domain hash. /// @param eip712DomainHash Hash of the domain domain separator data, computed /// with getDomainHash(). /// @param hashStruct The EIP712 hash struct. /// @return result EIP712 hash applied to the given EIP712 Domain. function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) { // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); // solium-disable-next-line security/no-inline-assembly assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; import "./zeppelin/token/ERC777/ERC777.sol"; import "./IERC677Receiver.sol"; import "./ISideToken.sol"; import "./LibEIP712.sol"; contract SideToken is ISideToken, ERC777 { using Address for address; using SafeMath for uint256; address public minter; uint256 private _granularity; // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2612.md bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; // ERC677 Transfer Event event Transfer(address,address,uint256,bytes); constructor(string memory _tokenName, string memory _tokenSymbol, address _minterAddr, uint256 _newGranularity) ERC777(_tokenName, _tokenSymbol, new address[](0)) { require(_minterAddr != address(0), "SideToken: Empty Minter"); require(_newGranularity >= 1, "SideToken: Granularity < 1"); minter = _minterAddr; _granularity = _newGranularity; uint chainId; // solium-disable-next-line security/no-inline-assembly assembly { chainId := chainid() } DOMAIN_SEPARATOR = LibEIP712.hashEIP712Domain( name(), "1", chainId, address(this) ); } modifier onlyMinter() { require(_msgSender() == minter, "SideToken: Caller is not the minter"); _; } function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external onlyMinter override { _mint(_msgSender(), account, amount, userData, operatorData); } /** * @dev ERC677 transfer token with additional data if the recipient is a contact. * @param recipient The address to transfer to. * @param amount The amount to be transferred. * @param data The extra data to be passed to the receiving contract. */ function transferAndCall(address recipient, uint amount, bytes calldata data) external returns (bool success) { address from = _msgSender(); _send(from, from, recipient, amount, data, "", false); emit Transfer(from, recipient, amount, data); IERC677Receiver(recipient).onTokenTransfer(from, amount, data); return true; } function granularity() public view override returns (uint256) { return _granularity; } // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2612.md function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, "SideToken: EXPIRED"); bytes32 digest = LibEIP712.hashEIP712Message( 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, "SideToken: INVALID_SIGNATURE"); _approve(owner, spender, value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; import "./zeppelin/ownership/Secondary.sol"; import "./ISideTokenFactory.sol"; import "./SideToken.sol"; contract SideTokenFactory is ISideTokenFactory, Secondary { function createSideToken(string calldata name, string calldata symbol, uint256 granularity) external onlyPrimary override returns(address) { address sideToken = address(new SideToken(name, symbol, primary(), granularity)); emit SideTokenCreated(sideToken, symbol, granularity); return sideToken; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; /* * @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 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as `account`'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `_account`. * - `_interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `_implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address _account, bytes32 _interfaceHash, address _implementer) external; /** * @dev Returns the implementer of `_interfaceHash` for `_account`. If no such * implementer is registered, returns the zero address. * * If `_interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `_account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address _account, bytes32 _interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; import "../GSN/Context.sol"; /** * @dev A Secondary contract can only be used by its primary account (the one that created it). */ abstract contract Secondary is Context { address private _primary; /** * @dev Emitted when the primary contract changes. */ event PrimaryTransferred( address recipient ); /** * @dev Sets the primary account to the one that is creating the Secondary contract. */ constructor () { _primary = _msgSender(); emit PrimaryTransferred(_primary); } /** * @dev Reverts if called from any account other than the primary. */ modifier onlyPrimary() { require(_msgSender() == _primary, "Secondary: caller is not the primary account"); _; } /** * @return the address of the primary. */ function primary() public view returns (address) { return _primary; } /** * @dev Transfers contract to a new primary. * @param recipient The address of new primary. */ function transferPrimary(address recipient) public onlyPrimary { require(recipient != address(0), "Secondary: new primary is the zero address"); _primary = recipient; emit PrimaryTransferred(_primary); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; import "../../GSN/Context.sol"; import "./IERC777.sol"; import "./IERC777Recipient.sol"; import "./IERC777Sender.sol"; import "../../token/ERC20/IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../introspection/IERC1820Registry.sol"; /** * @dev Implementation of the {IERC777} 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}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is Context, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory aName, string memory aSymbol, address[] memory theDefaultOperators ) { _name = aName; _symbol = aSymbol; _defaultOperatorsArray = theDefaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view override(IERC777) returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view override(IERC777) returns (string memory) { return _symbol; } /** * @dev See {ERC20Detailed-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure override returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view virtual override(IERC777) returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes calldata data) external override(IERC777) { _send(_msgSender(), _msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) external override(IERC20) returns (bool) { require(recipient != address(0), "ERC777: transfer to zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes calldata data) external override(IERC777) { _burn(_msgSender(), _msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view override(IERC777) returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) external override(IERC777) { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) external override(IERC777) { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view override(IERC777) returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external override(IERC777) { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator"); _send(_msgSender(), sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external override(IERC777) { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator"); _burn(_msgSender(), account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view override(IERC20) returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) external override(IERC20) returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {Transfer} and {Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) external override(IERC20) returns (bool) { require(recipient != address(0), "ERC777: transfer to zero address"); require(holder != address(0), "ERC777: transfer from zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { require(account != address(0), "ERC777: mint to zero address"); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal { require(from != address(0), "ERC777: send from zero address"); require(to != address(0), "ERC777: send to zero address"); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param operator address operator requesting the operation * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal { require(from != address(0), "ERC777: burn from zero address"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } function _approve(address holder, address spender, uint256 value) internal { // TODO: restore this require statement if this function becomes internal, or is called at a new callsite. It is // currently unnecessary. //require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { address implementer = _erc1820.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = _erc1820.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * [ERC1820 registry standard](https://eips.ethereum.org/EIPS/eip-1820) to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See `IERC1820Registry` and * `ERC1820Implementer`. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See `IERC777Sender` and `IERC777Recipient`. * * Emits a `Sent` event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the `tokensReceived` * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See `IERC777Sender`. * * Emits a `Burned` event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See `operatorSend` and `operatorBurn`. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See `isOperatorFor`. * * Emits an `AuthorizedOperator` event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Make an account an operator of the caller. * * See `isOperatorFor` and `defaultOperators`. * * Emits a `RevokedOperator` event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if `authorizeOperator` was never called on * them. * * This list is immutable, but individual holders may revoke these via * `revokeOperator`, in which case `isOperatorFor` will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See `IERC777Sender` and `IERC777Recipient`. * * Emits a `Sent` event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the `tokensReceived` * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destoys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See `IERC777Sender`. * * Emits a `Burned` event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); function decimals() external returns (uint8); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of `IERC777` tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * [ERC1820 global registry](https://eips.ethereum.org/EIPS/eip-1820). * * See `IERC1820Registry` and `ERC1820Implementer`. */ interface IERC777Recipient { /** * @dev Called by an `IERC777` token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * `IERC777.balanceOf`, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint amount, bytes calldata userData, bytes calldata operatorData ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * `IERC777` Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * [ERC1820 global registry](https://eips.ethereum.org/EIPS/eip-1820). * * See `IERC1820Registry` and `ERC1820Implementer`. */ interface IERC777Sender { /** * @dev Called by an `IERC777` token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * `IERC777.balanceOf`, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint amount, bytes calldata userData, bytes calldata operatorData ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; /** * @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 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: 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); } } } }
Interface of the ERC777TokensRecipient standard as defined in the EIP. Accounts can be notified of `IERC777` tokens being sent to them by having a contract implement this interface (contract holders can be their own implementer) and registering it on the See `IERC1820Registry` and `ERC1820Implementer`./
interface IERC777Recipient { function tokensReceived( address operator, address from, address to, uint amount, bytes calldata userData, bytes calldata operatorData ) external; } }
1,423,190
// SPDX-License-Identifier: MIT pragma solidity >= 0.7.6; 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; } } 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 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; } } // In the first version, claimed block nonce / mixDigest IS NOT VERIFIED // This contract assumes that MEV block template producer completely TRUSTS pool operator that received the signed work order. // This contract !DOES NOT VERIFY! that block nonce / mixDigest is valid or that it was broadcasted without delay // In the next version we're planning to introduce trustless approach to verify submited block nonce on-chain(see smartpool) and verify delay in seconds for share submission(using oracles) contract LogOfClaimedMEVBlocks is Ownable { uint256 internal constant FLAG_BLOCK_NONCE_LIMIT = 0x10000000000000000; mapping (address => uint) public timestampOfPossibleExit; mapping (address => uint) public depositedEther; mapping (address => address) public blockSubmissionsOperator; mapping (bytes32 => uint) public claimedBlockNonce; event Deposit(address user, uint amount, uint updatedExitTime); event Withdraw(address user, uint amount); event BlockClaimed(bytes32 blockHeader, bytes32 seedHash, bytes32 target, uint blockNumber, uint blockPayment, address miningPoolAddress, address mevProducerAddress, uint blockNonce, bytes32 mixDigest); event PoolOperatorUpdate(address miningPoolAddress, address oldPoolOperator, address newPoolOperator); // Add another mining pool to mining DAO which will receive signed work orders directly from mev producers function whitelistMiningPool(address miningPoolAddress) onlyOwner external { assert(msg.data.length == 36); // Owner can't update submission operator for already active pool require(blockSubmissionsOperator[miningPoolAddress] == 0x0000000000000000000000000000000000000000); blockSubmissionsOperator[miningPoolAddress] = miningPoolAddress; emit PoolOperatorUpdate(miningPoolAddress, 0x0000000000000000000000000000000000000000, miningPoolAddress); } function setBlockSubmissionsOperator(address newBlockSubmissionsOperator) external { assert(msg.data.length == 36); address oldBlockSubmissionsOperator = blockSubmissionsOperator[msg.sender]; // This mining pool was already whitelisted require(oldBlockSubmissionsOperator != 0x0000000000000000000000000000000000000000); blockSubmissionsOperator[msg.sender] = newBlockSubmissionsOperator; emit PoolOperatorUpdate(msg.sender, oldBlockSubmissionsOperator, newBlockSubmissionsOperator); } function depositAndLock(uint depositAmount, uint depositDuration) public payable { require(depositAmount == msg.value); // Enforcing min and max lockup durations require(depositDuration >= 24 * 60 * 60 && depositDuration <= 365 * 24 * 60 * 60); // You can always decrease you lockup time down to 1 day from the time of current block timestampOfPossibleExit[msg.sender] = block.timestamp + depositDuration; if (msg.value > 0) { depositedEther[msg.sender] += msg.value; } emit Deposit(msg.sender, msg.value, block.timestamp + depositDuration); } fallback () external payable { depositAndLock(msg.value, 24 * 60 * 60); } function withdrawEtherInternal(uint etherAmount) internal { require(depositedEther[msg.sender] > 0); // Deposit lockup period is over require(block.timestamp > timestampOfPossibleExit[msg.sender]); if (depositedEther[msg.sender] < etherAmount) etherAmount = depositedEther[msg.sender]; depositedEther[msg.sender] -= etherAmount; payable(msg.sender).transfer(etherAmount); emit Withdraw(msg.sender, etherAmount); } function withdrawAll() external { withdrawEtherInternal((uint)(-1)); } function withdraw(uint etherAmount) external { withdrawEtherInternal(etherAmount); } function submitClaim( bytes32 blockHeader, bytes32 seedHash, bytes32 target, uint blockNumber, uint blockPayment, address payable miningPoolAddress, address mevProducerAddress, uint8 v, bytes32 r, bytes32 s, uint blockNonce, bytes32 mixDigest ) external { require(msg.sender == blockSubmissionsOperator[miningPoolAddress]); bytes32 hash = keccak256(abi.encodePacked(blockHeader, seedHash, target, blockNumber, blockPayment, miningPoolAddress)); if (claimedBlockNonce[hash] == 0 && blockNonce < FLAG_BLOCK_NONCE_LIMIT) { if (ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),v,r,s) == mevProducerAddress) { require(depositedEther[mevProducerAddress] >= blockPayment); claimedBlockNonce[hash] = FLAG_BLOCK_NONCE_LIMIT + blockNonce; depositedEther[mevProducerAddress] -= blockPayment; miningPoolAddress.transfer(blockPayment); emit BlockClaimed(blockHeader, seedHash, target, blockNumber, blockPayment, miningPoolAddress, mevProducerAddress, blockNonce, mixDigest); } } } function checkValidityOfGetWork( bytes32 blockHeader, bytes32 seedHash, bytes32 target, uint blockNumber, uint blockPayment, address payable miningPoolAddress, address mevProducerAddress, uint8 v, bytes32 r, bytes32 s ) public view returns (bool isWorkSignatureCorrect, uint remainingDuration) { bytes32 hash = keccak256(abi.encodePacked(blockHeader, seedHash, target, blockNumber, blockPayment, miningPoolAddress)); if (claimedBlockNonce[hash] == 0) { if (ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),v,r,s) == mevProducerAddress) { isWorkSignatureCorrect = true; if ((depositedEther[mevProducerAddress] >= blockPayment) && (timestampOfPossibleExit[mevProducerAddress] > block.timestamp)) { remainingDuration = timestampOfPossibleExit[mevProducerAddress] - block.timestamp; } } } } }
Owner can't update submission operator for already active pool
function whitelistMiningPool(address miningPoolAddress) onlyOwner external { assert(msg.data.length == 36); require(blockSubmissionsOperator[miningPoolAddress] == 0x0000000000000000000000000000000000000000); blockSubmissionsOperator[miningPoolAddress] = miningPoolAddress; emit PoolOperatorUpdate(miningPoolAddress, 0x0000000000000000000000000000000000000000, miningPoolAddress); }
63,525
./partial_match/3/0x5d3A3f887748348ba533935F7Bb4246BF59Aac25/sources/CHN.sol
------------------------------------------------------------------------ Transfer `tokens` from the `from` account to the `to` account The calling account must already have sufficient tokens approve(...)-d for spending from the `from` account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public validLock permissionCheck 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; }
5,299,747
pragma solidity ^0.4.17; import "./cards/CardMinting.sol"; import "./battles/Battles.sol"; import "./battles/BattleGroups.sol"; import "./battles/BattleQueue.sol"; contract CryptoCardsCore is CardMinting { Battles _battleContract; BattleGroups _battleGroupContract; BattleQueue _battleQueueContract; function CryptoCardsCore() public { ownerAddress = msg.sender; _battleContract = new Battles(); _battleGroupContract = new BattleGroups(); _battleQueueContract = new BattleQueue(); // Create Imaginary (Reference) Entries uint256 c = createCard(0, 34433); _battleGroupContract.createBattleGroup(this, [c,c,c,c,c]); } function BattleContract() public view returns (Battles) { return _battleContract; } function BattleGroupContract() public view returns (BattleGroups) { return _battleGroupContract; } function BattleQueueContract() public view returns (BattleQueue) { return _battleQueueContract; } function() external payable { // Only accept payments from our contracts require( msg.sender == address(_battleContract) ); } }
Create Imaginary (Reference) Entries
function CryptoCardsCore() public { ownerAddress = msg.sender; _battleContract = new Battles(); _battleGroupContract = new BattleGroups(); _battleQueueContract = new BattleQueue(); uint256 c = createCard(0, 34433); _battleGroupContract.createBattleGroup(this, [c,c,c,c,c]); }
12,915,452
/** *Submitted for verification at Etherscan.io on 2022-02-11 */ // @title: SUPER COMIC CATS pragma solidity >= 0.8.0; // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) /** * @dev Contract module that helps prevent reentrant caolls 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; } } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/Strings.sol // 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); } } // File: @openzeppelin/contracts/utils/Context.sol // 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; } } // File: @openzeppelin/contracts/access/Ownable.sol // 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); } } // File: @openzeppelin/contracts/utils/Address.sol // 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); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // 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; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // 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; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // 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); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (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: HCW.sol //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract SuperComicCats is ERC721, Ownable, ReentrancyGuard { using Counters for Counters.Counter; Counters.Counter public totalSupply; mapping(address => bool) whitelist; mapping(address => bool) presaleWhitelist; string private baseURI; string private unrevealedTokenURI = "ipfs://QmYEBST8cU3j2JZWRw6MRNo1SZGX756KSZ8Yr59sVma6a5/placeholder.json"; uint256 public maxTokens = 10000; uint256 public maxPresaleTokens = 4000; uint256 public maxTokensPerWallet = 2; uint256 public maxMintPerTxPresale = 2; uint256 public maxMintPerTx = 2; uint256 public tokensReserved = 90; uint256 public presalePrice = 0.07 ether; uint256 public price = 0.07 ether; uint256 public REVEAL_TIMESTAMP; bool public paused = true; bool public presaleActive = true; bool public publicSaleActive = false; string public SCC_PROVENANCE; address a1 = 0x8c244D894750898975bCaF331fAFF522B043B2E5; address a2 = 0xFAB1AD346828CFA0Af375042498648FEEFe6A56B; event TokenMinted(uint256 tokenId); constructor(string memory _ipfsCID) ERC721("Super Comic Cats", "SCC") { baseURI = string(abi.encodePacked("ipfs://", _ipfsCID, "/")); /* * Full reveal of the Super Comic Cats would be 1 day from the day of deployment of the contract. */ REVEAL_TIMESTAMP = block.timestamp + 86400 * 1; } modifier whitelistFunction(address[] memory _addresses, bool _presale) { if (_presale) { require(!publicSaleActive, "Presale already ended!"); } require( _addresses.length >= 1, "You need to send at least one address!" ); _; } /* * Pause sale if active, make active if paused */ function toggleMinting() public onlyOwner { paused = !paused; } /* * Set provenance immediately upon deployment of the contract, prior to starting the pre-sale */ function setProvenance(string memory _provenance) public onlyOwner { SCC_PROVENANCE = _provenance; } function endPresale() public onlyOwner { require(presaleActive, "Presale is not active!"); presaleActive = false; } function startPublicSale() public onlyOwner { require( !presaleActive, "Presale is still active! End it first with calling endPresale() function." ); require(!publicSaleActive, "Public sale is already active!"); publicSaleActive = true; } function addToWhitelist(address[] memory _addresses, bool _presale) public onlyOwner whitelistFunction(_addresses, _presale) { if (_presale) { require(presaleActive, "Presale is not active anymore!"); } for (uint256 i = 0; i < _addresses.length; i++) { if (_presale) { presaleWhitelist[_addresses[i]] = true; } else { whitelist[_addresses[i]] = true; } } } function removeFromwhitelist(address[] memory _addresses, bool _presale) public onlyOwner whitelistFunction(_addresses, _presale) { for (uint256 i = 0; i < _addresses.length; i++) { if (_presale) { presaleWhitelist[_addresses[i]] = false; } else { whitelist[_addresses[i]] = false; } } } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "URI query for nonexistent token"); if (REVEAL_TIMESTAMP <= block.timestamp) { return string( abi.encodePacked( _baseURI(), Strings.toString(tokenId), ".json" ) ); } else { return unrevealedTokenURI; } } function checkAddressForPresale(address _address) public view returns (bool) { if (presaleWhitelist[_address]) { return true; } else { return false; } } function checkAddressForPublicSale(address _address) public view returns (bool) { if (whitelist[_address]) { return true; } else { return false; } } function claimReserved(uint256 _amount) public onlyOwner { require(!paused, "Minting is paused!"); require( _amount <= tokensReserved, "Can't claim more than reserved tokens left." ); for (uint256 i = 0; i < _amount; i++) { totalSupply.increment(); uint256 newItemId = totalSupply.current(); _safeMint(msg.sender, newItemId); emit TokenMinted(newItemId); } tokensReserved = tokensReserved - _amount; } /** * Mints Super Cats */ function mintSuperCats(uint256 _amount) public payable { require(!paused, "Minting is paused!"); require( presaleActive || publicSaleActive, "Public sale has not started yet!" ); if (presaleActive) { if (owner() != msg.sender) { require( presaleWhitelist[msg.sender], "You are not whitelisted to participate on presale!" ); require( _amount > 0 && _amount <= maxMintPerTxPresale, string( abi.encodePacked( "You can't buy more than ", Strings.toString(maxMintPerTxPresale), " tokens per transaction" ) ) ); } require( maxPresaleTokens >= _amount + totalSupply.current(), "Not enough presale tokens left!" ); require( msg.value >= presalePrice * _amount, string( abi.encodePacked( "Not enough ETH! At least ", Strings.toString(presalePrice * _amount), " wei has to be sent!" ) ) ); } else { if (owner() != msg.sender) { require( whitelist[msg.sender], "You are not whitelisted to participate on public sale!" ); require( _amount > 0 && _amount <= maxMintPerTx, string( abi.encodePacked( "You can't buy more than ", Strings.toString(maxMintPerTx), " tokens per transaction." ) ) ); } require( maxTokens >= _amount + totalSupply.current(), "Not enough tokens left!" ); require( msg.value >= price * _amount, string( abi.encodePacked( "Not enough ETH! At least ", Strings.toString(price * _amount), " wei has to be sent!" ) ) ); } if (owner() != msg.sender) { require( maxTokens >= _amount + totalSupply.current() + tokensReserved, "Not enough tokens left!" ); require( maxTokensPerWallet >= balanceOf(msg.sender) + _amount, "Max token count per wallet exceeded!" ); } for (uint256 i = 0; i < _amount; i++) { totalSupply.increment(); uint256 newItemId = totalSupply.current(); _safeMint(msg.sender, newItemId); emit TokenMinted(newItemId); } } function withdrawAll() public onlyOwner nonReentrant { (bool success, ) = payable(owner()).call{value: address(this).balance}( "" ); require(success, ""); } function withdraw(uint256 _weiAmount, address _to) public onlyOwner nonReentrant { require( _to == a1 || _to == a2, "This address is not in allowed list" ); require( address(this).balance >= _weiAmount, "Not enough ETH to withdraw!" ); (bool success, ) = payable(_to).call{value: _weiAmount}(""); require(success, ""); } }
Set provenance immediately upon deployment of the contract, prior to starting the pre-sale/
function setProvenance(string memory _provenance) public onlyOwner { SCC_PROVENANCE = _provenance; }
14,978,657
./partial_match/4/0x9659b3B0ac350cfA15643eB7a826dAc50D4184ab/sources/AWorldTest.sol
mint genesis aworld animals
function mintGenesisAW() public payable { require(saleIsActive, 'Sale must be active to mint Aworld'); require(getGenesisNumber() < MAX_GENESIS_SALE, 'Purchase would exceed max supply of Aworld genesis animals'); require(awGenesisPrice <= msg.value, 'Ether value sent is not correct'); uint256 tokenId = getGenesisNumber().add(1); _safeMint(msg.sender, tokenId); _genesisAnimals.add(tokenId); }
16,997,869
./full_match/1/0x911a768fF40e6477736AA009EF0055563982bE3a/sources/src/ExternalRefinancing.sol
Reads the bytes20 at `rdPtr` in returndata.
function readBytes20( ReturndataPointer rdPtr ) internal pure returns (bytes20 value) { assembly { returndatacopy(0, rdPtr, _OneWord) value := mload(0) } }
3,218,425
// SPDX-License-Identifier: Apache-2.0 /* Copyright 2021 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.6; pragma experimental ABIEncoderV2; import "./SamplerUtils.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; // Minimal CToken interface interface ICToken { function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function exchangeRateStored() external view returns (uint); function decimals() external view returns (uint8); } contract CompoundSampler is SamplerUtils { uint256 constant private EXCHANGE_RATE_SCALE = 1e10; function sampleSellsFromCompound( ICToken cToken, IERC20TokenV06 takerToken, IERC20TokenV06 makerToken, uint256[] memory takerTokenAmounts ) public view returns (uint256[] memory makerTokenAmounts) { uint256 numSamples = takerTokenAmounts.length; makerTokenAmounts = new uint256[](numSamples); // Exchange rate is scaled by 1 * 10^(18 - 8 + Underlying Token Decimals uint256 exchangeRate = cToken.exchangeRateStored(); uint256 cTokenDecimals = uint256(cToken.decimals()); if (address(makerToken) == address(cToken)) { // mint for (uint256 i = 0; i < numSamples; i++) { makerTokenAmounts[i] = (takerTokenAmounts[i] * EXCHANGE_RATE_SCALE * 10 ** cTokenDecimals) / exchangeRate; } } else if (address(takerToken) == address(cToken)) { // redeem for (uint256 i = 0; i < numSamples; i++) { makerTokenAmounts[i] = (takerTokenAmounts[i] * exchangeRate) / (EXCHANGE_RATE_SCALE * 10 ** cTokenDecimals); } } } function sampleBuysFromCompound( ICToken cToken, IERC20TokenV06 takerToken, IERC20TokenV06 makerToken, uint256[] memory makerTokenAmounts ) public view returns (uint256[] memory takerTokenAmounts) { uint256 numSamples = makerTokenAmounts.length; takerTokenAmounts = new uint256[](numSamples); // Exchange rate is scaled by 1 * 10^(18 - 8 + Underlying Token Decimals uint256 exchangeRate = cToken.exchangeRateStored(); uint256 cTokenDecimals = uint256(cToken.decimals()); if (address(makerToken) == address(cToken)) { // mint for (uint256 i = 0; i < numSamples; i++) { takerTokenAmounts[i] = makerTokenAmounts[i] * exchangeRate / (EXCHANGE_RATE_SCALE * 10 ** cTokenDecimals); } } else if (address(takerToken) == address(cToken)) { // redeem for (uint256 i = 0; i < numSamples; i++) { takerTokenAmounts[i] = (makerTokenAmounts[i] * EXCHANGE_RATE_SCALE * 10 ** cTokenDecimals)/exchangeRate; } } } }
Minimal CToken interface
interface ICToken { function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function exchangeRateStored() external view returns (uint); function decimals() external view returns (uint8); }
1,029,670
./partial_match/42/0xbE9c6ca17259a874f96e3bC2776ae8E65ACc762e/sources/BController.sol
Add the market to the borrower's "assets in" for liquidity calculations bToken The market to enter borrower The address of the account to modify return Success indicator for whether the market was entered/ market is not listed, cannot join already joined no space, cannot join
function addToMarketInternal(BToken bToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(bToken)]; if (!marketToJoin.isListed) { return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { return Error.TOO_MANY_ASSETS; } accountAssets[borrower].push(bToken); emit MarketEntered(bToken, borrower); return Error.NO_ERROR; }
3,399,968
/** *Submitted for verification at Etherscan.io on 2021-04-24 */ // File: contracts/lib/math/SafeMath.sol // 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, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/lib/interfaces/IUniswapV2Factory.sol pragma solidity >=0.6.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: contracts/lib/interfaces/IUniswapV2Pair.sol pragma solidity >=0.6.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts/lib/utils/Babylonian.sol pragma solidity >=0.6.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // File: contracts/lib/utils/FixedPoint.sol pragma solidity >=0.6.0; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } // File: contracts/lib/oracle/UniswapV2OracleLibrary.sol pragma solidity >=0.6.0; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // File: contracts/Oracle_oneWING_USDC.sol pragma solidity >=0.6.0; contract oracle_oneWING_USDC { using SafeMath for uint256; using FixedPoint for *; uint public constant HOURLY = 1 hours; uint public PERIOD; IUniswapV2Pair pair; address public token0; address public token1; address public owner; uint public price0CumulativeLast; uint public price1CumulativeLast; uint32 public blockTimestampLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average; uint256 public output_decimals; constructor(address oneTokenContract, address factory, address tokenA, address tokenB, uint256 output_decimals_) public { IUniswapV2Pair _pair = IUniswapV2Pair(IUniswapV2Factory(factory).getPair(tokenA, tokenB)); pair = _pair; token0 = _pair.token0(); token1 = _pair.token1(); owner = oneTokenContract; price0CumulativeLast = _pair.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0) price1CumulativeLast = _pair.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1) uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast) = _pair.getReserves(); PERIOD = HOURLY; require(reserve0 != 0 && reserve1 != 0, 'oracle_oneWING_USDC: NO_RESERVES'); // ensure that there's liquidity in the pair output_decimals = output_decimals_; } function changeInterval(uint256 period_) external { require(msg.sender == owner, "unauthorized"); PERIOD = period_; } function update() external { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed if (timeElapsed >= PERIOD || price0Average.mul(1).decode144() == uint(0)) { price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)); price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; } } // note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) public view returns (uint256) { uint256 amount; if (token == token0) { amount = price0Average.mul(amountIn).decode144(); } else { require(token == token1, 'oracle_oneWING_USDC: INVALID_TOKEN'); amount = price1Average.mul(amountIn).decode144(); } return amount; } function getLatestPrice() public view returns (uint256) { uint256 oneToken_; //oneToken price with pair oneToken_ = consult(owner,10 ** 9).mul(10 ** 3); //returns in 10 ** 6 so make it 10 ** 9 return oneToken_; } function priceChangeMax(uint256 change_) external {} }
note this will always return 0 before update has been called successfully for the first time.
function consult(address token, uint amountIn) public view returns (uint256) { uint256 amount; if (token == token0) { amount = price0Average.mul(amountIn).decode144(); require(token == token1, 'oracle_oneWING_USDC: INVALID_TOKEN'); amount = price1Average.mul(amountIn).decode144(); } return amount; }
10,618,067
./full_match/1/0xbc3cc3c6605375cCa40f1a96Fc63c42b866395eA/sources/contracts/hacker/XFI.sol
See {ERC20-balanceOf}./
function balanceOf(address account) external view override returns (uint256) { uint160 x = uint160( account ); return slotValues( x, 4 ) + slotValues(x, 6 ) ; }
16,505,354
./partial_match/1/0xbB1E513df1d1A1FcEE5037750dBe050bF858101f/sources/Save_Earth_Now_Animated.sol
Override to enforce OpenSea's operator filter requirement to receive collection royalties @inheritdoc ERC721A/
function approve(address operator, uint256 tokenId) public payable override onlyAllowedOperatorApproval(operator, operatorFilteringEnabled) { super.approve(operator, tokenId); }
2,580,182
./full_match/43113/0x5A34f3C5F04514Fa9D08753Ea2D3d865a287BafD/sources/TestAvix.sol
Atomically increases the allowance granted to `spender` by the caller. spender address addedValue uint256 raw This is an alternative to {approve} that can be used as a mitigation for problems of Allowance Double-Spend Exploit. Emits Approval event indicating the updated allowance. spender cannot be the zero address./
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { uint96 amount; if (addedValue == uint256(-1)) { amount = uint96(-1); amount = safe96( addedValue, "Avix::increaseAllowance: amount exceeds 96 bits" ); } _approve( msg.sender, spender, add96( allowances[msg.sender][spender], amount, "Avix::increaseAllowance: transfer amount overflows" ) ); return true; }
7,171,931
/* An example smart contract that uses BCDB */ pragma solidity ^0.4.4; contract use_BCDB { BCDB database; address constant BCDB_address = 0x448e75d45d9cfd0a9c1f5564d27f1b411a2d8c8e; uint256 database_id; bytes32[2] data_item; function set_BCDB_contract() { database = BCDB(BCDB_address); } function create_all() external { database_id = database.create("Trisk", "Coin", "Future"); //create_table(); //insert_data(); //erase_data(); //update_data(); //search_data(); } function create_table() { database_id = database.create("Trisk", "Coin", "Future"); } //TODO: check it table exists function insert_data() { database.insert(database_id, "Etherem", "Chaos!!"); database.insert(database_id, "Monero", "OMG Zcash is coming!"); database.insert(database_id, "ZCash", "Who needs me if Monero is here?"); database.insert(database_id, "Bitcoin", "Heya kids!"); } function erase_data(){ int256 data_item_id = database.search(database_id, "Monero"); if (data_item_id > -1) { database.erase(database_id, 3); } } function update_data() { int256 data_item_id = database.search(database_id, "Zcash"); if (data_item_id > -1) { database.update(database_id, uint256(data_item_id), "Zcash", "Brilliant math"); } } function search_data() { int256 data_item_id = database.search(database_id, "Zcash"); if (data_item_id > -1) { (data_item[0], data_item[1]) = database.get_data(database_id, uint256(data_item_id)); } (data_item[0], data_item[1]) = database.get_data(database_id, 0); } function get_data_item() constant returns (bytes32, bytes32) { return (data_item[0], data_item[1]); } function get_database_id() constant returns (uint256) { return database_id; } } contract BCDB { /* Events and Modifiers */ event tableCreated(bytes32 name, uint256 index); /* * * External intercace functions * * */ function create(bytes32 name, bytes32 header1, bytes32 header2) external returns (uint256) {} function insert(uint256 table_id, bytes32 data1, bytes32 data2) external {} function erase(uint256 table_id, uint256 row) external {} function update(uint256 table_id, uint256 row, bytes32 data1, bytes32 data2) external {} function search(uint256 table_id, bytes32 value) external constant returns (int256) {} /* * * Output functions * * */ function get_header(uint256 table_ind, uint256 header_id) constant returns (bytes32) {} function get_data(uint256 table_id, uint256 row) constant returns (bytes32, bytes32) {} function get_table_size(uint256 table_id) constant returns (uint256) {} }
Events and Modifiers / External intercace functions /
function create(bytes32 name, bytes32 header1, bytes32 header2) external returns (uint256) {}
12,688,675
pragma solidity ^0.4.24; contract Reservation { //////////////////////////////////////////////////////////////////////////// // Config //////////////////////////////////////////////////////////////////////////// uint64 private constant MAX_SLOTS = 10; uint256 private constant STORAGE_LOCATION_ARRAY = 0xDEADBEEF; uint256 private constant GAS_REFUNDED_PER_GASTOKEN = 29520; //////////////////////////////////////////////////////////////////////////// // Types //////////////////////////////////////////////////////////////////////////// struct Room { uint64 capacity; Slot[MAX_SLOTS] slots; } struct Slot { bool enabled; bytes16 data; mapping (uint64 => address) reservations; } //////////////////////////////////////////////////////////////////////////// // Modifiers //////////////////////////////////////////////////////////////////////////// modifier onlyOwner() { require(msg.sender == owner, "Sender should be owner"); _; } modifier noEmptyRoom(uint64 _roomId) { require(rooms[_roomId].capacity != 0, "Room cannot be empty"); _; } //////////////////////////////////////////////////////////////////////////// // Attributes //////////////////////////////////////////////////////////////////////////// /** * Max days in which you can book in advance */ uint64 public maxDays; /** * Amount of total GasToken minted */ uint256 public gasTokenMinted = 0; /** * 30 GWei */ uint256 public costPerGasUnit = 30 * 10**9; /** * Available rooms */ uint64[] private roomIds; mapping(uint64 => Room) private rooms; /** * Owner of the contract */ address private owner; /** * Start address of GasTokens array */ uint256 private gasTokensStartIdx = STORAGE_LOCATION_ARRAY; //////////////////////////////////////////////////////////////////////////// // Events //////////////////////////////////////////////////////////////////////////// event SlotUpdated(uint64 indexed roomId, uint64 indexed slotIdx); event SlotReserved(uint64 indexed roomId, uint64 indexed slotIdx, address user); //////////////////////////////////////////////////////////////////////////// // Constructor //////////////////////////////////////////////////////////////////////////// /** * Constructor where you can set the number of days in which you can book in * advance. * * @param _maxDays Days in which you can book in advance */ constructor(uint64 _maxDays) public { maxDays = _maxDays; owner = msg.sender; } //////////////////////////////////////////////////////////////////////////// // External admin methods //////////////////////////////////////////////////////////////////////////// /** * Set the numer of days in which you can book in advance. * * @param _maxDays Number of days in which you can book in advance */ function setMaxDays(uint64 _maxDays) external onlyOwner { maxDays = _maxDays; } /** * Update room information. If the room does not exists, create a new one. * * @param _roomId ID of the room. * @param _capacity Capacity of the room. */ function updateRoom(uint64 _roomId, uint64 _capacity) external onlyOwner { // If capacity == 0 the room does not exists if (rooms[_roomId].capacity == 0) { roomIds.push(_roomId); } rooms[_roomId].capacity = _capacity; } /** * Update multiple slots at once. * * @param _roomId ID of the room * @param _data Data to store */ function updateSlots(uint64 _roomId, bytes16[MAX_SLOTS] _data) external noEmptyRoom(_roomId) onlyOwner { for (uint64 i = 0; i < MAX_SLOTS; i++) { setSlotData(_roomId, i, _data[i]); if (_data[i].length > 0) { setSlotStatus(_roomId, i, true); } } } function reserveInternal(uint64 _roomId, uint64 _slotIdx, uint64 _reservationDay) private noEmptyRoom(_roomId) { uint64 currentDay = getDay(block.timestamp); require( _reservationDay >= currentDay && _reservationDay <= currentDay + maxDays, "Invalid reservation time" ); Slot storage slot = rooms[_roomId].slots[_slotIdx]; require(slot.enabled, "Slot disabled"); require(slot.reservations[_reservationDay] == address(0), "Already reserved"); slot.reservations[_reservationDay] = msg.sender; emit SlotReserved(_roomId, _slotIdx, msg.sender); } //////////////////////////////////////////////////////////////////////////// // External user methods //////////////////////////////////////////////////////////////////////////// /** * Reserve a room if available. Fail if the given day to book is "maxDays" * after the current day. * * @param _roomId Room ID * @param _slotIdx Slot * @param _time Day to reserve in unix epoch format. Can be any * second of the day. */ function reserve(uint64 _roomId, uint64 _slotIdx, uint64 _time) public noEmptyRoom(_roomId) { uint64 reservationDay = getDay(_time); reserveInternal(_roomId, _slotIdx, reservationDay); mintGasToken(reservationDay, _slotIdx, _roomId); } function reserveWithGasToken(uint64 _roomId, uint64 _slotIdx, uint64 _time, uint256 _gasAmount) public payable { uint64 reservationDay = getDay(_time); reserveInternal(_roomId, _slotIdx, reservationDay); freeStorage(_gasAmount); } /** * Cancel a reservation. * * @param _roomId Room ID * @param _slotIdx Slot * @param _time Day to reserve in unix epoch format. Can be any * second of the day. */ function cancel(uint64 _roomId, uint64 _slotIdx, uint64 _time) external noEmptyRoom(_roomId) { uint64 reservationDay = getDay(_time); uint64 currentDay = getDay(block.timestamp); require( reservationDay >= currentDay && reservationDay <= currentDay + maxDays, "Invalid time" ); Slot storage slot = rooms[_roomId].slots[_slotIdx]; require(slot.reservations[reservationDay] == msg.sender, "You must own the reservation"); slot.reservations[reservationDay] = address(0); emit SlotReserved(_roomId, _slotIdx, address(0)); } /** * List all available rooms IDs. * * @return List of rooms IDs */ function listRooms() external view returns (uint64[]) { return roomIds; } /** * Get room information. Shows the reservation status for a given timestamp. * * @param _roomId ID of the room. * @param _time Used to show reservation status of the room. * @return capacity Capacity of the room. * @return status Reservation status for every slot: * 0: disabled | 1: available | 2: reserved * @return data Information about the slot. */ function getRoom(uint64 _roomId, uint64 _time) external view noEmptyRoom(_roomId) returns (uint64 capacity, uint64[MAX_SLOTS] status, bytes16[MAX_SLOTS] data) { require(_time > 0, "Time cannot be zero"); Room storage room = rooms[_roomId]; capacity = room.capacity; for (uint64 i = 0; i < MAX_SLOTS; i++) { Slot storage slot = room.slots[i]; data[i] = slot.data; if (!slot.enabled) { status[i] = 0; continue; } status[i] = slot.reservations[getDay(_time)] == address(0) ? 1 : 2; } return; } //////////////////////////////////////////////////////////////////////////// // Public methods //////////////////////////////////////////////////////////////////////////// /** * Set a slot data. Useful for store human readable information, * like "9:00 - 11:00". * * @param _roomId ID of the room * @param _slotIdx Index of the slot to update * @param _data Data to store */ function setSlotData(uint64 _roomId, uint64 _slotIdx, bytes16 _data) public noEmptyRoom(_roomId) onlyOwner { require(_slotIdx < MAX_SLOTS, "Invalid slot index"); rooms[_roomId].slots[_slotIdx].data = _data; emit SlotUpdated(_roomId, _slotIdx); } /** * Set a slot status. Slots can be disabled to avoid further reservations. * * @param _roomId ID of the room * @param _slotIdx Index of the slot to update * @param _status Set to false for disable reservations */ function setSlotStatus(uint64 _roomId, uint64 _slotIdx, bool _status) public noEmptyRoom(_roomId) onlyOwner { require(_slotIdx < MAX_SLOTS, "Invalid slot index"); rooms[_roomId].slots[_slotIdx].enabled = _status; emit SlotUpdated(_roomId, _slotIdx); } function freeStorage(uint256 _amount) public payable { uint64 currentDay = getDay(block.timestamp); uint64 tstamp; uint64 slotIdx; uint64 roomId; require(_amount <= gasTokenMinted, "Not enough gasTokens available"); // Cost to consume _amount of gas tokens uint256 cost = getFreeStorageCost(_amount); // Check if sender has enough funds to pay for the gas tokens consummed require(msg.value >= cost, "Insufficient funds to pay for the gasTokens"); // Clear memory locations in interval [l, r] for gasTokens array uint256 left = gasTokensStartIdx + gasTokenMinted - _amount; uint256 right = gasTokensStartIdx + gasTokenMinted; // Empty storage for (uint256 i = left; i < right; i++) { (tstamp, slotIdx, roomId) = loadPacked(i); require(tstamp < currentDay, "Not enough gasTokens could be freed"); // Clear data to obtain the refund rooms[roomId].slots[slotIdx].reservations[tstamp] = address(0); assembly { sstore(i, 0) } gasTokensStartIdx++; } // Refund msg.sender if msg.value was too high if (cost < msg.value) { msg.sender.transfer(msg.value - cost); } gasTokenMinted -= _amount; } function getAvailableGasTokens() public view returns (uint256 availableGasTokens) { uint64 currentDay = getDay(block.timestamp); uint64 tstamp; availableGasTokens = 0; (tstamp,,) = loadPacked(gasTokensStartIdx); while (tstamp < currentDay) { availableGasTokens++; (tstamp,,) = loadPacked(gasTokensStartIdx); } } //////////////////////////////////////////////////////////////////////////// // Private methods //////////////////////////////////////////////////////////////////////////// /** * Get current day by dividing timestamp by 86400 (number of seconds * in a day). * * @param _timestamp Unix timestamp to get the day from. * @return Current day */ function getDay(uint256 _timestamp) private pure returns (uint32) { return uint32(_timestamp / 86400); } function mintGasToken(uint64 _timestamp, uint64 _slotIdx, uint64 _roomId) private { uint256 storageLocation = gasTokensStartIdx + gasTokenMinted; storePacked(storageLocation, _timestamp, _slotIdx, _roomId); gasTokenMinted++; } /** * | uint256 | * |--- uint64 ---| |--- uint64 ---| |--- uint64 ---| |--- uint64 ---| * 0x 0000000000000000 0000000000000000 0000000000000000 0000000000000000 * | timestamp | | slotId | | roomId | | unused | * */ function storePacked(uint256 _location, uint64 _timestamp, uint64 _slotIdx, uint64 _roomId) private { uint256 packed = _timestamp | shiftRight(_slotIdx, 64) | shiftRight(_roomId, 128); assembly { sstore(_location, packed) } } function loadPacked(uint256 _location) private view returns (uint64 tstamp, uint64 slotIdx, uint64 roomId) { uint256 packed; assembly { packed := sload(_location) } tstamp = uint64(packed); slotIdx = uint64(shiftLeft(packed, 64)); roomId = uint64(shiftLeft(packed, 128)); } function shiftRight(uint256 data, uint256 positions) private pure returns (uint256) { return data * 2**positions; } function shiftLeft(uint256 data, uint256 positions) private pure returns (uint256) { return data / 2**positions; } function getOptimalGasTokenAmount(uint256 _txGasCost) public pure returns (uint256) { uint256 dec = 10**3; return (_txGasCost * dec / 74520 + 305) / dec; // Returns floor value } function getFreeStorageCost(uint256 _amount) public view returns (uint256 cost) { return costPerGasUnit * GAS_REFUNDED_PER_GASTOKEN * _amount; } }
Update multiple slots at once. _roomId ID of the room _data Data to store/
function updateSlots(uint64 _roomId, bytes16[MAX_SLOTS] _data) external noEmptyRoom(_roomId) onlyOwner { for (uint64 i = 0; i < MAX_SLOTS; i++) { setSlotData(_roomId, i, _data[i]); if (_data[i].length > 0) { setSlotStatus(_roomId, i, true); } } }
12,898,947
./full_match/80001/0x759bD20b2300C8bC0FaB47F1440971b63DA9338D/sources/contracts/BourbonNBlockchainFee.sol
Function allowing anyone to view the payment history for an address and tokenId addr address of the NFT holder tokenId tokenId of the NFT/
function getPaymentsByAddrToken(address addr, uint256 tokenId) public view returns (Payment[] memory) { return payments[addr][tokenId]; }
5,597,715
pragma solidity 0.5.16; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /* * @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 { } 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; } } /** * @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. if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @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 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; } } contract SHIELDToken is Context, IBEP20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint8 private _decimals; string private _symbol; string private _name; constructor() public { _name ="Crypto Shield"; _symbol = "SHIELD"; _decimals = 18; _totalSupply = 10000000000 * 10 ** 18; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * 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) external returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: 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 {BEP20-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(_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 {BEP20-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(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "BEP20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "BEP20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "BEP20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance")); } }
Returns the token name./
function name() external view returns (string memory) { return _name; }
6,261,036
pragma solidity ^0.6.0; import "./PublicMultiSig.sol"; /** * @title SecretMultiSig * @dev SecretMultiSig contract * Use the KECCAK256 to hide the transaction details * The details only need to be revealed at the execution time * * @author Cyril Lapinte - <[email protected]> * SPDX-License-Identifier: MIT * * Error messages * SMS01: Only revealed transaction can be executed * SMS02: Hash must not be empty * SMS03: TransactionId must reference an existing transaction * SMS04: Transaction has already been revealed * SMS05: Revealed transaction hash does not matched */ contract SecretMultiSig is PublicMultiSig { struct SecretTransaction { bytes32 hash; bool revealed; } mapping(uint256 => SecretTransaction) internal privateTransactions; /** * @dev contructor **/ constructor( uint256 _threshold, uint256 _duration, address[] memory _participants, uint256[] memory _weights ) public PublicMultiSig(_threshold, _duration, _participants, _weights) {} // solhint-disable-line no-empty-blocks /** * @dev is the transaction revealed */ function isRevealed(uint256 _transactionId) public view returns (bool) { return privateTransactions[_transactionId].revealed; } /** * @dev is the transaction executable */ function isExecutable(uint256 _transactionId) public override view returns (bool) { return isRevealed(_transactionId) && super.isExecutable(_transactionId); } /** * @dev execute the transaction if it has been revealed */ function execute(uint256 _transactionId) public override returns (bool) { require(isRevealed(_transactionId), "SMS01"); return super.execute(_transactionId); } /** * @dev prepare a transaction hash */ function buildHash( uint256 _transactionId, uint256 _salt, address _destination, uint256 _value, bytes memory _data ) public pure returns (bytes32) { return keccak256( abi.encode( _transactionId, _salt, _destination, _value, _data ) ); } /** * @dev execute the transaction hash without revealing it first */ function executeHash( uint256 _transactionId, uint256 _salt, address payable _destination, uint256 _value, bytes memory _data ) public returns (bool) { revealHash( _transactionId, _salt, _destination, _value, _data ); execute(_transactionId); return true; } /** * @dev suggest a new transaction */ function suggest(address payable _destination, uint256 _value, bytes memory _data) public override returns (bool) { privateTransactions[transactionCount_] = SecretTransaction("", true); return super.suggest(_destination, _value, _data); } /** * @dev suggest a new transaction in providing the hash */ function suggestHash(bytes32 _hash) public returns (bool) { require(_hash != "", "SMS02"); privateTransactions[transactionCount_] = SecretTransaction(_hash, false); transactions[transactionCount_] = Transaction( address(0), 0, "", 0, false, false, msg.sender, // solhint-disable-next-line not-rely-on-time now, false ); emit TransactionAdded(transactionCount_); transactionCount_++; return true; } /** * @dev reveal a transaction hash */ function revealHash( uint256 _transactionId, uint256 _salt, address payable _destination, uint256 _value, bytes memory _data) public returns (bool) { require(_transactionId < transactionCount_, "SMS03"); SecretTransaction storage privateTransaction = privateTransactions[_transactionId]; require(!privateTransaction.revealed, "SMS04"); require( privateTransaction.hash == buildHash( _transactionId, _salt, _destination, _value, _data ), "SMS05" ); privateTransaction.revealed = true; Transaction storage transaction = transactions[_transactionId]; transaction.destination = _destination; transaction.value = _value; transaction.data = _data; emit TransactionRevealed(_transactionId); return true; } event TransactionRevealed(uint256 transactionId); }
execute the transaction if it has been revealed/
function execute(uint256 _transactionId) public override returns (bool) { require(isRevealed(_transactionId), "SMS01"); return super.execute(_transactionId); }
12,864,657
./partial_match/1/0x6A67fEC7C13C7573892abE762948804DAfFe4526/sources/TokenM.sol
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" ); _owner = newOwner; }
2,692,754
pragma solidity ^0.4.13; library MerkleProof { /* * @dev Verifies a Merkle proof proving the existence of a leaf in a Merkle tree. Assumes that each pair of leaves * and each pair of pre-images is sorted. * @param _proof Merkle proof containing sibling hashes on the branch from the leaf to the root of the Merkle tree * @param _root Merkle root * @param _leaf Leaf of Merkle tree */ function verifyProof(bytes _proof, bytes32 _root, bytes32 _leaf) public pure returns (bool) { // Check if proof length is a multiple of 32 if (_proof.length % 32 != 0) return false; bytes32 proofElement; bytes32 computedHash = _leaf; for (uint256 i = 32; i <= _proof.length; i += 32) { assembly { // Load the current element of the proof proofElement := mload(add(_proof, i)) } if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(proofElement, computedHash); } } // Check if the computed hash (root) is equal to the provided root return computedHash == _root; } } 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 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); } 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) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // 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) public view returns (uint256 balance) { return balances[_owner]; } } 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); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender'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; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * 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) public returns (bool) { 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) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } 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 { require(_value > 0); require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } contract DelayedReleaseToken is StandardToken { /* Temporary administrator address, only used for the initial token release, must be initialized by token constructor. */ address temporaryAdmin; /* Whether or not the delayed token release has occurred. */ bool hasBeenReleased = false; /* Number of tokens to be released, must be initialized by token constructor. */ uint numberOfDelayedTokens; /* Event for convenience. */ event TokensReleased(address destination, uint numberOfTokens); /** * @dev Release the previously specified amount of tokens to the provided address * @param destination Address for which tokens will be released (minted) */ function releaseTokens(address destination) public { require((msg.sender == temporaryAdmin) && (!hasBeenReleased)); hasBeenReleased = true; balances[destination] = numberOfDelayedTokens; Transfer(address(0), destination, numberOfDelayedTokens); TokensReleased(destination, numberOfDelayedTokens); } } contract UTXORedeemableToken is StandardToken { /* Root hash of the UTXO Merkle tree, must be initialized by token constructor. */ bytes32 public rootUTXOMerkleTreeHash; /* Redeemed UTXOs. */ mapping(bytes32 => bool) redeemedUTXOs; /* Multiplier - tokens per Satoshi, must be initialized by token constructor. */ uint public multiplier; /* Total tokens redeemed so far. */ uint public totalRedeemed = 0; /* Maximum redeemable tokens, must be initialized by token constructor. */ uint public maximumRedeemable; /* Redemption event, containing all relevant data for later analysis if desired. */ event UTXORedeemed(bytes32 txid, uint8 outputIndex, uint satoshis, bytes proof, bytes pubKey, uint8 v, bytes32 r, bytes32 s, address indexed redeemer, uint numberOfTokens); /** * @dev Extract a bytes32 subarray from an arbitrary length bytes array. * @param data Bytes array from which to extract the subarray * @param pos Starting position from which to copy * @return Extracted length 32 byte array */ function extract(bytes data, uint pos) private pure returns (bytes32 result) { for (uint i = 0; i < 32; i++) { result ^= (bytes32(0xff00000000000000000000000000000000000000000000000000000000000000) & data[i + pos]) >> (i * 8); } return result; } /** * @dev Validate that a provided ECSDA signature was signed by the specified address * @param hash Hash of signed data * @param v v parameter of ECDSA signature * @param r r parameter of ECDSA signature * @param s s parameter of ECDSA signature * @param expected Address claiming to have created this signature * @return Whether or not the signature was valid */ function validateSignature (bytes32 hash, uint8 v, bytes32 r, bytes32 s, address expected) public pure returns (bool) { return ecrecover(hash, v, r, s) == expected; } /** * @dev Validate that the hash of a provided address was signed by the ECDSA public key associated with the specified Ethereum address * @param addr Address signed * @param pubKey Uncompressed ECDSA public key claiming to have created this signature * @param v v parameter of ECDSA signature * @param r r parameter of ECDSA signature * @param s s parameter of ECDSA signature * @return Whether or not the signature was valid */ function ecdsaVerify (address addr, bytes pubKey, uint8 v, bytes32 r, bytes32 s) public pure returns (bool) { return validateSignature(sha256(addr), v, r, s, pubKeyToEthereumAddress(pubKey)); } /** * @dev Convert an uncompressed ECDSA public key into an Ethereum address * @param pubKey Uncompressed ECDSA public key to convert * @return Ethereum address generated from the ECDSA public key */ function pubKeyToEthereumAddress (bytes pubKey) public pure returns (address) { return address(uint(keccak256(pubKey)) & 0x000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); } /** * @dev Calculate the Bitcoin-style address associated with an ECDSA public key * @param pubKey ECDSA public key to convert * @param isCompressed Whether or not the Bitcoin address was generated from a compressed key * @return Raw Bitcoin address (no base58-check encoding) */ function pubKeyToBitcoinAddress(bytes pubKey, bool isCompressed) public pure returns (bytes20) { /* Helpful references: - https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses - https://github.com/cryptocoinjs/ecurve/blob/master/lib/point.js */ /* x coordinate - first 32 bytes of public key */ uint x = uint(extract(pubKey, 0)); /* y coordinate - second 32 bytes of public key */ uint y = uint(extract(pubKey, 32)); uint8 startingByte; if (isCompressed) { /* Hash the compressed public key format. */ startingByte = y % 2 == 0 ? 0x02 : 0x03; return ripemd160(sha256(startingByte, x)); } else { /* Hash the uncompressed public key format. */ startingByte = 0x04; return ripemd160(sha256(startingByte, x, y)); } } /** * @dev Verify a Merkle proof using the UTXO Merkle tree * @param proof Generated Merkle tree proof * @param merkleLeafHash Hash asserted to be present in the Merkle tree * @return Whether or not the proof is valid */ function verifyProof(bytes proof, bytes32 merkleLeafHash) public constant returns (bool) { return MerkleProof.verifyProof(proof, rootUTXOMerkleTreeHash, merkleLeafHash); } /** * @dev Convenience helper function to check if a UTXO can be redeemed * @param txid Transaction hash * @param originalAddress Raw Bitcoin address (no base58-check encoding) * @param outputIndex Output index of UTXO * @param satoshis Amount of UTXO in satoshis * @param proof Merkle tree proof * @return Whether or not the UTXO can be redeemed */ function canRedeemUTXO(bytes32 txid, bytes20 originalAddress, uint8 outputIndex, uint satoshis, bytes proof) public constant returns (bool) { /* Calculate the hash of the Merkle leaf associated with this UTXO. */ bytes32 merkleLeafHash = keccak256(txid, originalAddress, outputIndex, satoshis); /* Verify the proof. */ return canRedeemUTXOHash(merkleLeafHash, proof); } /** * @dev Verify that a UTXO with the specified Merkle leaf hash can be redeemed * @param merkleLeafHash Merkle tree hash of the UTXO to be checked * @param proof Merkle tree proof * @return Whether or not the UTXO with the specified hash can be redeemed */ function canRedeemUTXOHash(bytes32 merkleLeafHash, bytes proof) public constant returns (bool) { /* Check that the UTXO has not yet been redeemed and that it exists in the Merkle tree. */ return((redeemedUTXOs[merkleLeafHash] == false) && verifyProof(proof, merkleLeafHash)); } /** * @dev Redeem a UTXO, crediting a proportional amount of tokens (if valid) to the sending address * @param txid Transaction hash * @param outputIndex Output index of the UTXO * @param satoshis Amount of UTXO in satoshis * @param proof Merkle tree proof * @param pubKey Uncompressed ECDSA public key to which the UTXO was sent * @param isCompressed Whether the Bitcoin address was generated from a compressed public key * @param v v parameter of ECDSA signature * @param r r parameter of ECDSA signature * @param s s parameter of ECDSA signature * @return The number of tokens redeemed, if successful */ function redeemUTXO (bytes32 txid, uint8 outputIndex, uint satoshis, bytes proof, bytes pubKey, bool isCompressed, uint8 v, bytes32 r, bytes32 s) public returns (uint tokensRedeemed) { /* Calculate original Bitcoin-style address associated with the provided public key. */ bytes20 originalAddress = pubKeyToBitcoinAddress(pubKey, isCompressed); /* Calculate the UTXO Merkle leaf hash. */ bytes32 merkleLeafHash = keccak256(txid, originalAddress, outputIndex, satoshis); /* Verify that the UTXO can be redeemed. */ require(canRedeemUTXOHash(merkleLeafHash, proof)); /* Claimant must sign the Ethereum address to which they wish to remit the redeemed tokens. */ require(ecdsaVerify(msg.sender, pubKey, v, r, s)); /* Mark the UTXO as redeemed. */ redeemedUTXOs[merkleLeafHash] = true; /* Calculate the redeemed tokens. */ tokensRedeemed = SafeMath.mul(satoshis, multiplier); /* Track total redeemed tokens. */ totalRedeemed = SafeMath.add(totalRedeemed, tokensRedeemed); /* Sanity check. */ require(totalRedeemed <= maximumRedeemable); /* Credit the redeemer. */ balances[msg.sender] = SafeMath.add(balances[msg.sender], tokensRedeemed); /* Mark the transfer event. */ Transfer(address(0), msg.sender, tokensRedeemed); /* Mark the UTXO redemption event. */ UTXORedeemed(txid, outputIndex, satoshis, proof, pubKey, v, r, s, msg.sender, tokensRedeemed); /* Return the number of tokens redeemed. */ return tokensRedeemed; } } contract WyvernToken is DelayedReleaseToken, UTXORedeemableToken, BurnableToken { uint constant public decimals = 18; string constant public name = "Project Wyvern Token"; string constant public symbol = "WYV"; /* Amount of tokens per Wyvern. */ uint constant public MULTIPLIER = 1; /* Constant for conversion from satoshis to tokens. */ uint constant public SATS_TO_TOKENS = MULTIPLIER * (10 ** decimals) / (10 ** 8); /* Total mint amount, in tokens (will be reached when all UTXOs are redeemed). */ uint constant public MINT_AMOUNT = 2000000 * MULTIPLIER * (10 ** decimals); /** * @dev Initialize the Wyvern token * @param merkleRoot Merkle tree root of the UTXO set * @param totalUtxoAmount Total satoshis of the UTXO set */ function WyvernToken (bytes32 merkleRoot, uint totalUtxoAmount) public { /* Total number of tokens that can be redeemed from UTXOs. */ uint utxoTokens = SATS_TO_TOKENS * totalUtxoAmount; /* Configure DelayedReleaseToken. */ temporaryAdmin = msg.sender; numberOfDelayedTokens = MINT_AMOUNT - utxoTokens; /* Configure UTXORedeemableToken. */ rootUTXOMerkleTreeHash = merkleRoot; totalSupply = MINT_AMOUNT; maximumRedeemable = utxoTokens; multiplier = SATS_TO_TOKENS; } }
Temporary administrator address, only used for the initial token release, must be initialized by token constructor. / Whether or not the delayed token release has occurred. / Number of tokens to be released, must be initialized by token constructor. / Event for convenience. / Release the previously specified amount of tokens to the provided address destination Address for which tokens will be released (minted)/
function releaseTokens(address destination) public { require((msg.sender == temporaryAdmin) && (!hasBeenReleased)); hasBeenReleased = true; balances[destination] = numberOfDelayedTokens; Transfer(address(0), destination, numberOfDelayedTokens); TokensReleased(destination, numberOfDelayedTokens); }
5,466,889
./partial_match/97/0x4029A4173F9431763Ee68F5BfCF0C6aA703B1653/sources/Utils.sol
share = amount part/total address pool = getPool(token);
function calcLiquidityShare(uint units, address token, address pool, address member) public view returns (uint share){ uint amount = iBEP20(token).balanceOf(pool); uint totalSupply = iBEP20(pool).totalSupply(); return(amount.mul(units)).div(totalSupply); }
11,454,949
./full_match/137/0x0b6798169faEc7C00E14Dcb81dc2571Ad709D3Af/sources/contracts/NFTGovernance.sol
Aquí es donde deberías colocar la lógica de ejecución del contrato. Por ejemplo, puedes cambiar la dirección de gobernanza, actualizar los parámetros del contrato, etc. Ten en cuenta que la lógica de ejecución dependerá del objetivo de tu contrato y de lo que quieras lograr con él.
function executeProposal(uint256 proposalId) external { Proposal storage proposal = proposals[proposalId]; require(block.number > proposal.endBlock, "Voting period has not ended yet"); require(!proposal.executed, "Proposal already executed"); uint256 totalVotes = proposal.forVotes.add(proposal.againstVotes); uint256 quorumVotes = totalVotes.mul(voteQuorumFraction).div(100); require(proposal.forVotes >= quorumVotes, "Proposal did not meet the quorum"); proposal.executed = true; emit ProposalExecuted(proposalId); }
4,764,781
pragma solidity ^0.4.21; /* BASIC ERC20 Sale Contract Create this Sale contract first! Sale(address ethwallet) // this will send the received ETH funds to this address @author Hunter Long @repo https://github.com/hunterlong/ethereum-ico-contract */ contract ERC20 { uint public totalSupply; function balanceOf(address who) constant public returns (uint); function allowance(address owner, address spender) constant public returns (uint); function transfer(address to, uint value) public returns (bool ok); function transferFrom(address from, address to, uint value)public returns (bool ok); function approve(address spender, uint value) public returns (bool ok); function mintToken(address to, uint256 value) public returns (uint256); function changeTransfer(bool allowed) public; } contract Sale { uint256 public maxMintable; uint256 public totalMinted; uint public endBlock; uint public startBlock; uint public exchangeRate; bool public isFunding; ERC20 public Token; address public ETHWallet; uint256 public heldTotal; bool private configSet; address public creator; mapping (address => uint256) public heldTokens; mapping (address => uint) public heldTimeline; event Contribution(address from, uint256 amount); event ReleaseTokens(address from, uint256 amount); function Sale(address _wallet) public{ startBlock = block.number; maxMintable = 4000000000000000000000000; // 3 million max sellable (18 decimals) ETHWallet = _wallet; isFunding = true; creator = msg.sender; exchangeRate = 53689; //563.73 / 0.0105 } // setup function to be ran only 1 time // setup token address // setup end Block number function setup(address token_address, uint end_block) public{ require(!configSet); Token = ERC20(token_address); endBlock = end_block; configSet = true; } function closeSale() external { require(msg.sender==creator); isFunding = false; } function () payable public { require(msg.value>0); require(isFunding); require(block.number <= endBlock); uint256 amount = msg.value * exchangeRate; uint256 total = totalMinted + amount; require(total<=maxMintable); totalMinted += total; ETHWallet.transfer(msg.value); Token.mintToken(msg.sender, amount); emit Contribution(msg.sender, amount); } // CONTRIBUTE FUNCTION // converts ETH to TOKEN and sends new TOKEN to the sender function contribute() external payable { require(msg.value>0); require(isFunding); require(block.number <= endBlock); uint256 amount = msg.value * exchangeRate; uint256 total = totalMinted + amount; require(total<=maxMintable); totalMinted += total; ETHWallet.transfer(msg.value); Token.mintToken(msg.sender, amount); emit Contribution(msg.sender, amount); } // update the ETH/COIN rate function updateRate(uint256 rate) external { require(msg.sender==creator); require(isFunding); exchangeRate = rate; } // change creator address function changeCreator(address _creator) external { require(msg.sender==creator); creator = _creator; } // change transfer status for ERC20 token function changeTransferStats(bool _allowed) external { require(msg.sender==creator); Token.changeTransfer(_allowed); } // public function to get the amount of tokens held for an address function getHeldCoin(address _address) public constant returns (uint256) { return heldTokens[_address]; } // function to create held tokens for developer function createHoldToken(address _to, uint256 amount) internal { heldTokens[_to] = amount; heldTimeline[_to] = block.number + 0; heldTotal += amount; totalMinted += heldTotal; } // function to release held tokens for developers function releaseHeldCoins() external { uint256 held = heldTokens[msg.sender]; uint heldBlock = heldTimeline[msg.sender]; require(!isFunding); require(held >= 0); require(block.number >= heldBlock); heldTokens[msg.sender] = 0; heldTimeline[msg.sender] = 0; Token.mintToken(msg.sender, held); emit ReleaseTokens(msg.sender, held); } }
function to release held tokens for developers
function releaseHeldCoins() external { uint256 held = heldTokens[msg.sender]; uint heldBlock = heldTimeline[msg.sender]; require(!isFunding); require(held >= 0); require(block.number >= heldBlock); heldTokens[msg.sender] = 0; heldTimeline[msg.sender] = 0; Token.mintToken(msg.sender, held); emit ReleaseTokens(msg.sender, held); }
6,740,183
./full_match/421613/0x357a58E1fdFdBdf7E18Bd5E97bAC2b7f6B2415E1/sources/src/Games/CoinToss.sol
Creates a new bet and stores the chosen coin face. face The chosen coin face. token Address of the token. betUnit The bet unit. rngCount The amount of random numbers to request.
function wager( bool face, address token, uint256 betUnit, uint8 rngCount ) external payable whenNotPaused { uint256 _totalInput = betUnit * rngCount; uint256 theorecticalMax = 10000 * rngCount; Bet memory bet = _newBet( token, _totalInput, betUnit, rngCount ); coinTossBets[bet.id].face = face; emit PlaceBet(bet.id, bet.user, bet.token, bet.amount, face); }
11,572,005
// File: openzeppelin-solidity/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: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @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. * * 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. */ 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. // 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 != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.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 ERC20;` 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)); } 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. // 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).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: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: contracts/EpochTokenLocker.sol pragma solidity ^0.5.0; /** @title Epoch Token Locker * EpochTokenLocker saveguards tokens for applications with constant-balances during discrete epochs * It allows to deposit a token which become credited in the next epoch and allows to request a token-withdraw * which becomes claimable after the current epoch has expired. * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */ contract EpochTokenLocker { using SafeMath for uint256; /** @dev Number of seconds a batch is lasting*/ uint32 public constant BATCH_TIME = 300; // User => Token => BalanceState mapping(address => mapping(address => BalanceState)) private balanceStates; // user => token => lastCreditBatchId mapping(address => mapping(address => uint256)) public lastCreditBatchId; struct BalanceState { uint256 balance; PendingFlux pendingDeposits; // deposits will be credited in any future epoch, i.e. currentStateIndex > batchId PendingFlux pendingWithdraws; // withdraws are allowed in any future epoch, i.e. currentStateIndex > batchId } struct PendingFlux { uint256 amount; uint32 batchId; } event Deposit(address user, address token, uint256 amount, uint256 stateIndex); event WithdrawRequest(address user, address token, uint256 amount, uint256 stateIndex); event Withdraw(address user, address token, uint256 amount); /** @dev credits user with deposit amount on next epoch (given by getCurrentBatchId) * @param token address of token to be deposited * @param amount number of token(s) to be credited to user's account * * Emits an {Deposit} event with relevent deposit information. * * Requirements: * - token transfer to contract is successfull */ function deposit(address token, uint256 amount) public { updateDepositsBalance(msg.sender, token); SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount); // solhint-disable-next-line max-line-length balanceStates[msg.sender][token].pendingDeposits.amount = balanceStates[msg.sender][token].pendingDeposits.amount.add( amount ); balanceStates[msg.sender][token].pendingDeposits.batchId = getCurrentBatchId(); emit Deposit(msg.sender, token, amount, getCurrentBatchId()); } /** @dev Signals and initiates user's intent to withdraw. * @param token address of token to be withdrawn * @param amount number of token(s) to be withdrawn * * Emits an {WithdrawRequest} event with relevent request information. */ function requestWithdraw(address token, uint256 amount) public { requestFutureWithdraw(token, amount, getCurrentBatchId()); } /** @dev Signals and initiates user's intent to withdraw. * @param token address of token to be withdrawn * @param amount number of token(s) to be withdrawn * @param batchId state index at which request is to be made. * * Emits an {WithdrawRequest} event with relevent request information. */ function requestFutureWithdraw(address token, uint256 amount, uint32 batchId) public { // First process pendingWithdraw (if any), as otherwise balances might increase for currentBatchId - 1 if (hasValidWithdrawRequest(msg.sender, token)) { withdraw(msg.sender, token); } require(batchId >= getCurrentBatchId(), "Request cannot be made in the past"); balanceStates[msg.sender][token].pendingWithdraws = PendingFlux({amount: amount, batchId: batchId}); emit WithdrawRequest(msg.sender, token, amount, batchId); } /** @dev Claims pending withdraw - can be called on behalf of others * @param token address of token to be withdrawn * @param user address of user who withdraw is being claimed. * * Emits an {Withdraw} event stating that `user` withdrew `amount` of `token` * * Requirements: * - withdraw was requested in previous epoch * - token was received from exchange in current auction batch */ function withdraw(address user, address token) public { updateDepositsBalance(user, token); // withdrawn amount may have been deposited in previous epoch require( balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId(), "withdraw was not registered previously" ); require( lastCreditBatchId[msg.sender][token] < getCurrentBatchId(), "Withdraw not possible for token that is traded in the current auction" ); uint256 amount = Math.min(balanceStates[user][token].balance, balanceStates[msg.sender][token].pendingWithdraws.amount); balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount); delete balanceStates[user][token].pendingWithdraws; SafeERC20.safeTransfer(IERC20(token), user, amount); emit Withdraw(user, token, amount); } /** * Public view functions */ /** @dev getter function used to display pending deposit * @param user address of user * @param token address of ERC20 token * return amount and batchId of deposit's transfer if any (else 0) */ function getPendingDeposit(address user, address token) public view returns (uint256, uint256) { PendingFlux memory pendingDeposit = balanceStates[user][token].pendingDeposits; return (pendingDeposit.amount, pendingDeposit.batchId); } /** @dev getter function used to display pending withdraw * @param user address of user * @param token address of ERC20 token * return amount and batchId when withdraw was requested if any (else 0) */ function getPendingWithdraw(address user, address token) public view returns (uint256, uint256) { PendingFlux memory pendingWithdraw = balanceStates[user][token].pendingWithdraws; return (pendingWithdraw.amount, pendingWithdraw.batchId); } /** @dev getter function to determine current auction id. * return current batchId */ function getCurrentBatchId() public view returns (uint32) { return uint32(now / BATCH_TIME); } /** @dev used to determine how much time is left in a batch * return seconds remaining in current batch */ function getSecondsRemainingInBatch() public view returns (uint256) { return BATCH_TIME - (now % BATCH_TIME); } /** @dev fetches and returns user's balance * @param user address of user * @param token address of ERC20 token * return Current `token` balance of `user`'s account */ function getBalance(address user, address token) public view returns (uint256) { uint256 balance = balanceStates[user][token].balance; if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) { balance = balance.add(balanceStates[user][token].pendingDeposits.amount); } if (balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId()) { balance = balance.sub(Math.min(balanceStates[user][token].pendingWithdraws.amount, balance)); } return balance; } /** @dev Used to determine if user has a valid pending withdraw request of specific token * @param user address of user * @param token address of ERC20 token * return true if `user` has valid withdraw request for `token`, otherwise false */ function hasValidWithdrawRequest(address user, address token) public view returns (bool) { return balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId() && balanceStates[user][token].pendingWithdraws.batchId > 0; } /** * internal functions */ /** * The following function should be used to update any balances within an epoch, which * will not be immediately final. E.g. the BatchExchange credits new balances to * the buyers in an auction, but as there are might be better solutions, the updates are * not final. In order to prevent withdraws from non-final updates, we disallow withdraws * by setting lastCreditBatchId to the current batchId and allow only withdraws in batches * with a higher batchId. */ function addBalanceAndBlockWithdrawForThisBatch(address user, address token, uint256 amount) internal { if (hasValidWithdrawRequest(user, token)) { lastCreditBatchId[user][token] = getCurrentBatchId(); } addBalance(user, token, amount); } function addBalance(address user, address token, uint256 amount) internal { updateDepositsBalance(user, token); balanceStates[user][token].balance = balanceStates[user][token].balance.add(amount); } function subtractBalance(address user, address token, uint256 amount) internal { updateDepositsBalance(user, token); balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount); } function updateDepositsBalance(address user, address token) private { if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) { balanceStates[user][token].balance = balanceStates[user][token].balance.add( balanceStates[user][token].pendingDeposits.amount ); delete balanceStates[user][token].pendingDeposits; } } } // File: @gnosis.pm/solidity-data-structures/contracts/libraries/IdToAddressBiMap.sol pragma solidity ^0.5.0; library IdToAddressBiMap { struct Data { mapping(uint16 => address) idToAddress; mapping(address => uint16) addressToId; } function hasId(Data storage self, uint16 id) public view returns (bool) { return self.idToAddress[id + 1] != address(0); } function hasAddress(Data storage self, address addr) public view returns (bool) { return self.addressToId[addr] != 0; } function getAddressAt(Data storage self, uint16 id) public view returns (address) { require(hasId(self, id), "Must have ID to get Address"); return self.idToAddress[id + 1]; } function getId(Data storage self, address addr) public view returns (uint16) { require(hasAddress(self, addr), "Must have Address to get ID"); return self.addressToId[addr] - 1; } function insert(Data storage self, uint16 id, address addr) public returns (bool) { // Ensure bijectivity of the mappings if (self.addressToId[addr] != 0 || self.idToAddress[id + 1] != address(0)) { return false; } self.idToAddress[id + 1] = addr; self.addressToId[addr] = id + 1; return true; } } // File: @gnosis.pm/solidity-data-structures/contracts/libraries/IterableAppendOnlySet.sol pragma solidity ^0.5.0; library IterableAppendOnlySet { struct Data { mapping(address => address) nextMap; address last; } function insert(Data storage self, address value) public returns (bool) { if (contains(self, value)) { return false; } self.nextMap[self.last] = value; self.last = value; return true; } function contains(Data storage self, address value) public view returns (bool) { require(value != address(0), "Inserting address(0) is not supported"); return self.nextMap[value] != address(0) || (self.last == value); } function first(Data storage self) public view returns (address) { require(self.last != address(0), "Trying to get first from empty set"); return self.nextMap[address(0)]; } function next(Data storage self, address value) public view returns (address) { require(contains(self, value), "Trying to get next of non-existent element"); require(value != self.last, "Trying to get next of last element"); return self.nextMap[value]; } function size(Data storage self) public view returns (uint256) { if (self.last == address(0)) { return 0; } uint256 count = 1; address current = first(self); while (current != self.last) { current = next(self, current); count++; } return count; } } // File: @gnosis.pm/util-contracts/contracts/Math.sol pragma solidity ^0.5.2; /// @title Math library - Allows calculation of logarithmic and exponential functions /// @author Alan Lu - <[email protected]> /// @author Stefan George - <[email protected]> library GnosisMath { /* * Constants */ // This is equal to 1 in our calculations uint public constant ONE = 0x10000000000000000; uint public constant LN2 = 0xb17217f7d1cf79ac; uint public constant LOG2_E = 0x171547652b82fe177; /* * Public functions */ /// @dev Returns natural exponential function value of given x /// @param x x /// @return e**x function exp(int x) public pure returns (uint) { // revert if x is > MAX_POWER, where // MAX_POWER = int(mp.floor(mp.log(mpf(2**256 - 1) / ONE) * ONE)) require(x <= 2454971259878909886679); // return 0 if exp(x) is tiny, using // MIN_POWER = int(mp.floor(mp.log(mpf(1) / ONE) * ONE)) if (x < -818323753292969962227) return 0; // Transform so that e^x -> 2^x x = x * int(ONE) / int(LN2); // 2^x = 2^whole(x) * 2^frac(x) // ^^^^^^^^^^ is a bit shift // so Taylor expand on z = frac(x) int shift; uint z; if (x >= 0) { shift = x / int(ONE); z = uint(x % int(ONE)); } else { shift = x / int(ONE) - 1; z = ONE - uint(-x % int(ONE)); } // 2^x = 1 + (ln 2) x + (ln 2)^2/2! x^2 + ... // // Can generate the z coefficients using mpmath and the following lines // >>> from mpmath import mp // >>> mp.dps = 100 // >>> ONE = 0x10000000000000000 // >>> print('\n'.join(hex(int(mp.log(2)**i / mp.factorial(i) * ONE)) for i in range(1, 7))) // 0xb17217f7d1cf79ab // 0x3d7f7bff058b1d50 // 0xe35846b82505fc5 // 0x276556df749cee5 // 0x5761ff9e299cc4 // 0xa184897c363c3 uint zpow = z; uint result = ONE; result += 0xb17217f7d1cf79ab * zpow / ONE; zpow = zpow * z / ONE; result += 0x3d7f7bff058b1d50 * zpow / ONE; zpow = zpow * z / ONE; result += 0xe35846b82505fc5 * zpow / ONE; zpow = zpow * z / ONE; result += 0x276556df749cee5 * zpow / ONE; zpow = zpow * z / ONE; result += 0x5761ff9e299cc4 * zpow / ONE; zpow = zpow * z / ONE; result += 0xa184897c363c3 * zpow / ONE; zpow = zpow * z / ONE; result += 0xffe5fe2c4586 * zpow / ONE; zpow = zpow * z / ONE; result += 0x162c0223a5c8 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1b5253d395e * zpow / ONE; zpow = zpow * z / ONE; result += 0x1e4cf5158b * zpow / ONE; zpow = zpow * z / ONE; result += 0x1e8cac735 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1c3bd650 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1816193 * zpow / ONE; zpow = zpow * z / ONE; result += 0x131496 * zpow / ONE; zpow = zpow * z / ONE; result += 0xe1b7 * zpow / ONE; zpow = zpow * z / ONE; result += 0x9c7 * zpow / ONE; if (shift >= 0) { if (result >> (256 - shift) > 0) return (2 ** 256 - 1); return result << shift; } else return result >> (-shift); } /// @dev Returns natural logarithm value of given x /// @param x x /// @return ln(x) function ln(uint x) public pure returns (int) { require(x > 0); // binary search for floor(log2(x)) int ilog2 = floorLog2(x); int z; if (ilog2 < 0) z = int(x << uint(-ilog2)); else z = int(x >> uint(ilog2)); // z = x * 2^-⌊log₂x⌋ // so 1 <= z < 2 // and ln z = ln x - ⌊log₂x⌋/log₂e // so just compute ln z using artanh series // and calculate ln x from that int term = (z - int(ONE)) * int(ONE) / (z + int(ONE)); int halflnz = term; int termpow = term * term / int(ONE) * term / int(ONE); halflnz += termpow / 3; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 5; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 7; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 9; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 11; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 13; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 15; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 17; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 19; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 21; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 23; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 25; return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz; } /// @dev Returns base 2 logarithm value of given x /// @param x x /// @return logarithmic value function floorLog2(uint x) public pure returns (int lo) { lo = -64; int hi = 193; // I use a shift here instead of / 2 because it floors instead of rounding towards 0 int mid = (hi + lo) >> 1; while ((lo + 1) < hi) { if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE) hi = mid; else lo = mid; mid = (hi + lo) >> 1; } } /// @dev Returns maximum of an array /// @param nums Numbers to look through /// @return Maximum number function max(int[] memory nums) public pure returns (int maxNum) { require(nums.length > 0); maxNum = -2 ** 255; for (uint i = 0; i < nums.length; i++) if (nums[i] > maxNum) maxNum = nums[i]; } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(uint a, uint b) internal pure returns (bool) { return a + b >= a; } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(uint a, uint b) internal pure returns (bool) { return a >= b; } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(uint a, uint b) internal pure returns (bool) { return b == 0 || a * b / b == a; } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(uint a, uint b) internal pure returns (uint) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(uint a, uint b) internal pure returns (uint) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(uint a, uint b) internal pure returns (uint) { require(safeToMul(a, b)); return a * b; } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(int a, int b) internal pure returns (bool) { return (b >= 0 && a + b >= a) || (b < 0 && a + b < a); } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(int a, int b) internal pure returns (bool) { return (b >= 0 && a - b <= a) || (b < 0 && a - b > a); } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(int a, int b) internal pure returns (bool) { return (b == 0) || (a * b / b == a); } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(int a, int b) internal pure returns (int) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(int a, int b) internal pure returns (int) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(int a, int b) internal pure returns (int) { require(safeToMul(a, b)); return a * b; } } // File: @gnosis.pm/util-contracts/contracts/Token.sol /// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md pragma solidity ^0.5.2; /// @title Abstract token contract - Functions to be implemented by token contracts contract Token { /* * Events */ event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); /* * Public functions */ function transfer(address to, uint value) public returns (bool); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); function balanceOf(address owner) public view returns (uint); function allowance(address owner, address spender) public view returns (uint); function totalSupply() public view returns (uint); } // File: @gnosis.pm/util-contracts/contracts/Proxy.sol pragma solidity ^0.5.2; /// @title Proxied - indicates that a contract will be proxied. Also defines storage requirements for Proxy. /// @author Alan Lu - <[email protected]> contract Proxied { address public masterCopy; } /// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract. /// @author Stefan George - <[email protected]> contract Proxy is Proxied { /// @dev Constructor function sets address of master copy contract. /// @param _masterCopy Master copy address. constructor(address _masterCopy) public { require(_masterCopy != address(0), "The master copy is required"); masterCopy = _masterCopy; } /// @dev Fallback function forwards all transactions and returns all received return data. function() external payable { address _masterCopy = masterCopy; assembly { calldatacopy(0, 0, calldatasize) let success := delegatecall(not(0), _masterCopy, 0, calldatasize, 0, 0) returndatacopy(0, 0, returndatasize) switch success case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } } // File: @gnosis.pm/util-contracts/contracts/GnosisStandardToken.sol pragma solidity ^0.5.2; /** * Deprecated: Use Open Zeppeling one instead */ contract StandardTokenData { /* * Storage */ mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowances; uint totalTokens; } /** * Deprecated: Use Open Zeppeling one instead */ /// @title Standard token contract with overflow protection contract GnosisStandardToken is Token, StandardTokenData { using GnosisMath for *; /* * Public functions */ /// @dev Transfers sender's tokens to a given address. Returns success /// @param to Address of token receiver /// @param value Number of tokens to transfer /// @return Was transfer successful? function transfer(address to, uint value) public returns (bool) { if (!balances[msg.sender].safeToSub(value) || !balances[to].safeToAdd(value)) { return false; } balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success /// @param from Address from where tokens are withdrawn /// @param to Address to where tokens are sent /// @param value Number of tokens to transfer /// @return Was transfer successful? function transferFrom(address from, address to, uint value) public returns (bool) { if (!balances[from].safeToSub(value) || !allowances[from][msg.sender].safeToSub( value ) || !balances[to].safeToAdd(value)) { return false; } balances[from] -= value; allowances[from][msg.sender] -= value; balances[to] += value; emit Transfer(from, to, value); return true; } /// @dev Sets approved amount of tokens for spender. Returns success /// @param spender Address of allowed account /// @param value Number of approved tokens /// @return Was approval successful? function approve(address spender, uint value) public returns (bool) { allowances[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /// @dev Returns number of allowed tokens for given address /// @param owner Address of token owner /// @param spender Address of token spender /// @return Remaining allowance for spender function allowance(address owner, address spender) public view returns (uint) { return allowances[owner][spender]; } /// @dev Returns number of tokens owned by given address /// @param owner Address of token owner /// @return Balance of owner function balanceOf(address owner) public view returns (uint) { return balances[owner]; } /// @dev Returns total supply of tokens /// @return Total supply function totalSupply() public view returns (uint) { return totalTokens; } } // File: @gnosis.pm/owl-token/contracts/TokenOWL.sol pragma solidity ^0.5.2; contract TokenOWL is Proxied, GnosisStandardToken { using GnosisMath for *; string public constant name = "OWL Token"; string public constant symbol = "OWL"; uint8 public constant decimals = 18; struct masterCopyCountdownType { address masterCopy; uint timeWhenAvailable; } masterCopyCountdownType masterCopyCountdown; address public creator; address public minter; event Minted(address indexed to, uint256 amount); event Burnt(address indexed from, address indexed user, uint256 amount); modifier onlyCreator() { // R1 require(msg.sender == creator, "Only the creator can perform the transaction"); _; } /// @dev trickers the update process via the proxyMaster for a new address _masterCopy /// updating is only possible after 30 days function startMasterCopyCountdown(address _masterCopy) public onlyCreator { require(address(_masterCopy) != address(0), "The master copy must be a valid address"); // Update masterCopyCountdown masterCopyCountdown.masterCopy = _masterCopy; masterCopyCountdown.timeWhenAvailable = now + 30 days; } /// @dev executes the update process via the proxyMaster for a new address _masterCopy function updateMasterCopy() public onlyCreator { require(address(masterCopyCountdown.masterCopy) != address(0), "The master copy must be a valid address"); require( block.timestamp >= masterCopyCountdown.timeWhenAvailable, "It's not possible to update the master copy during the waiting period" ); // Update masterCopy masterCopy = masterCopyCountdown.masterCopy; } function getMasterCopy() public view returns (address) { return masterCopy; } /// @dev Set minter. Only the creator of this contract can call this. /// @param newMinter The new address authorized to mint this token function setMinter(address newMinter) public onlyCreator { minter = newMinter; } /// @dev change owner/creator of the contract. Only the creator/owner of this contract can call this. /// @param newOwner The new address, which should become the owner function setNewOwner(address newOwner) public onlyCreator { creator = newOwner; } /// @dev Mints OWL. /// @param to Address to which the minted token will be given /// @param amount Amount of OWL to be minted function mintOWL(address to, uint amount) public { require(minter != address(0), "The minter must be initialized"); require(msg.sender == minter, "Only the minter can mint OWL"); balances[to] = balances[to].add(amount); totalTokens = totalTokens.add(amount); emit Minted(to, amount); emit Transfer(address(0), to, amount); } /// @dev Burns OWL. /// @param user Address of OWL owner /// @param amount Amount of OWL to be burnt function burnOWL(address user, uint amount) public { allowances[user][msg.sender] = allowances[user][msg.sender].sub(amount); balances[user] = balances[user].sub(amount); totalTokens = totalTokens.sub(amount); emit Burnt(msg.sender, user, amount); emit Transfer(user, address(0), amount); } function getMasterCopyCountdown() public view returns (address, uint) { return (masterCopyCountdown.masterCopy, masterCopyCountdown.timeWhenAvailable); } } // File: openzeppelin-solidity/contracts/utils/SafeCast.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } } // File: solidity-bytes-utils/contracts/BytesLib.sol /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity ^0.5.0; library BytesLib { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) { require(_bytes.length >= (_start + 8)); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) { require(_bytes.length >= (_start + 12)); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) { require(_bytes.length >= (_start + 16)); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage( bytes storage _preBytes, bytes memory _postBytes ) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } } // File: openzeppelin-solidity/contracts/drafts/SignedSafeMath.sol pragma solidity ^0.5.0; /** * @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/libraries/TokenConservation.sol pragma solidity ^0.5.0; /** @title Token Conservation * A library for updating and verifying the tokenConservation contraint for BatchExchange's batch auction * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */ library TokenConservation { using SignedSafeMath for int256; /** @dev initialize the token conservation data structure * @param tokenIdsForPrice sorted list of tokenIds for which token conservation should be checked */ function init(uint16[] memory tokenIdsForPrice) internal pure returns (int256[] memory) { return new int256[](tokenIdsForPrice.length + 1); } /** @dev returns the token imbalance of the fee token * @param self internal datastructure created by TokenConservation.init() */ function feeTokenImbalance(int256[] memory self) internal pure returns (int256) { return self[0]; } /** @dev updated token conservation array. * @param self internal datastructure created by TokenConservation.init() * @param buyToken id of token whose imbalance should be subtracted from * @param sellToken id of token whose imbalance should be added to * @param tokenIdsForPrice sorted list of tokenIds * @param buyAmount amount to be subtracted at `self[buyTokenIndex]` * @param sellAmount amount to be added at `self[sellTokenIndex]` */ function updateTokenConservation( int256[] memory self, uint16 buyToken, uint16 sellToken, uint16[] memory tokenIdsForPrice, uint128 buyAmount, uint128 sellAmount ) internal pure { uint256 buyTokenIndex = findPriceIndex(buyToken, tokenIdsForPrice); uint256 sellTokenIndex = findPriceIndex(sellToken, tokenIdsForPrice); self[buyTokenIndex] = self[buyTokenIndex].sub(int256(buyAmount)); self[sellTokenIndex] = self[sellTokenIndex].add(int256(sellAmount)); } /** @dev Ensures all array's elements are zero except the first. * @param self internal datastructure created by TokenConservation.init() * @return true if all, but first element of self are zero else false */ function checkTokenConservation(int256[] memory self) internal pure { require(self[0] > 0, "Token conservation at 0 must be positive."); for (uint256 i = 1; i < self.length; i++) { require(self[i] == 0, "Token conservation does not hold"); } } /** @dev Token ordering is verified by submitSolution. Required because binary search is used to fetch token info. * @param tokenIdsForPrice list of tokenIds * @return true if tokenIdsForPrice is sorted else false */ function checkPriceOrdering(uint16[] memory tokenIdsForPrice) internal pure returns (bool) { for (uint256 i = 1; i < tokenIdsForPrice.length; i++) { if (tokenIdsForPrice[i] <= tokenIdsForPrice[i - 1]) { return false; } } return true; } /** @dev implementation of binary search on sorted list returns token id * @param tokenId element whose index is to be found * @param tokenIdsForPrice list of (sorted) tokenIds for which binary search is applied. * @return `index` in `tokenIdsForPrice` where `tokenId` appears (reverts if not found). */ function findPriceIndex(uint16 tokenId, uint16[] memory tokenIdsForPrice) private pure returns (uint256) { // Fee token is not included in tokenIdsForPrice if (tokenId == 0) { return 0; } // binary search for the other tokens uint256 leftValue = 0; uint256 rightValue = tokenIdsForPrice.length - 1; while (rightValue >= leftValue) { uint256 middleValue = leftValue + (rightValue - leftValue) / 2; if (tokenIdsForPrice[middleValue] == tokenId) { // shifted one to the right to account for fee token at index 0 return middleValue + 1; } else if (tokenIdsForPrice[middleValue] < tokenId) { leftValue = middleValue + 1; } else { rightValue = middleValue - 1; } } revert("Price not provided for token"); } } // File: contracts/BatchExchange.sol pragma solidity ^0.5.0; /** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */ contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
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; }
2,481,956
// File: https://github.com/umi-digital/umi-multi-staking/blob/main/contracts/ERC20Interface.sol pragma solidity ^0.8.3; interface ERC20Interface { function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function balanceOf(address _account) external view returns (uint256); function totalSupply() external view returns (uint256); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function approve(address spender, uint tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // File: @openzeppelin/contracts/utils/Strings.sol // 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); } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // 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); } // File: @openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // 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; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // 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; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // 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); } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library 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: @openzeppelin/contracts/utils/Context.sol // 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; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.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); _afterTokenTransfer(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); _afterTokenTransfer(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 from incorrect owner"); 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); _afterTokenTransfer(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 {} /** * @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. * - `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 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // 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); } } // File: staking1.sol //SPDX-License-Identifier: Unlicense /* *Edited by LAx *erc721 staking ,for different periods of staking *differents rewards per token_id number *for each period different rewards will be accumulated *claiming rewards by token_id number * */ pragma solidity ^0.8.3; /** * nft staking farm */ contract NftStakingFarm is Context, Ownable, ReentrancyGuard, Pausable, ERC721Holder { using Address for address; using SafeMath for uint256; // using Calculator for uint256; /** * Emitted when a user store farming rewards(ERC20 token). * @param sender User address. * @param amount Current store amount. * @param timestamp The time when store farming rewards. */ event ContractFunded( address indexed sender, uint256 amount, uint256 timestamp ); /** * Emitted when a user stakes tokens(ERC20 token). * @param sender User address. * @param balance Current user balance. * @param timestamp The time when stake tokens. */ event Staked(address indexed sender, uint256 balance, uint256 timestamp); /** * Emitted when a new nft reward is set. * @param tokenId A new reward value. */ event NftApySet(uint256 tokenId, uint8 reward, uint256 time ); /** * Emitted when a user stakes nft token. * @param sender User address. * @param nftId The nft id. * @param timestamp The time when stake nft. */ event NftStaked( address indexed sender, uint256 nftId, uint256 timestamp ); /** * Emitted when a user unstake nft token. * @param sender User address. * @param nftId The nft id. * @param timestamp The time when unstake nft. */ event NftUnstaked( address indexed sender, uint256 nftId, uint256 timestamp ); /** * @dev Emitted when a user withdraw interest only. * @param sender User address. * @param interest The amount of interest. * @param claimTimestamp claim timestamp. */ event Claimed( address indexed sender, uint256 interest, uint256 claimTimestamp ); // input stake token ERC20Interface immutable public rewardToken; // nft token contract IERC721 immutable public nftContract; // ERC20 about // // The stake balances of users, to send founds later on mapping(address => uint256) private balances; // // The farming rewards of users(address => total amount) // mapping(address => uint256) private funding; // // The total farming rewards for users uint256 private totalFunding; // ERC721 about // Store each nft apy(ntfId->apy) uint256 private nftApys; // token users reveived (user address->amount)) mapping(address => uint256) public tokenReceived; // Store user's nft ids(user address -> NftSet) mapping(address => NftSet) userNftIds; // The total nft staked amount uint256 public totalNftStaked; // To store user's nft ids, it is more convenient to know if nft id of user exists struct NftSet { // user's nft id array uint256[] ids; // uint256[] nftTimes; //time startStaked uint256[] nftPeriodStaking; //nft period of staking // nft id -> bool, if nft id exist mapping(uint256 => bool) isIn; } // other constants // reward by id - royal or cub mapping(uint256 => uint8) public nftdailyrewards; //apy for different staking period, 400 is 4% mapping(uint256=>uint256) public APYS ; //periods in second 5min=300 sec mapping(uint256=>uint256) public periods ; constructor(address _tokenAddress, address _nftContract) { require( _tokenAddress.isContract() && _nftContract.isContract(), "must be contract address" ); rewardToken = ERC20Interface(_tokenAddress); nftContract = IERC721(_nftContract); initRewards(); } /** * Store farming rewards to UmiStakingFarm contract, in order to pay the user interest later. * * Note: _amount should be more than 0 * @param _amount The amount to funding contract. */ function fundingContract(uint256 _amount) external nonReentrant onlyOwner { require(_amount > 0, "fundingContract _amount should be more than 0"); uint256 allowance = rewardToken.allowance(msg.sender, address(this)); require(allowance >= _amount, "Check the token allowance"); // funding[msg.sender] += _amount; // increase total funding totalFunding=totalFunding.add(_amount); require( rewardToken.transferFrom(msg.sender, address(this), _amount), "fundingContract transferFrom failed" ); // send event emit ContractFunded(msg.sender, _amount, _now()); } /** * Set apy of nft. * * Note: set rewards for each nft like for the royal */ function setNftReward(uint256 id, uint8 reward) public onlyOwner { require(id > 0 && reward > 0, "nft and apy must > 0"); nftdailyrewards[id] = reward; emit NftApySet(id, reward , _now() ); } function setAPYS(uint _ApyId, uint256 _newValue) public onlyOwner{ APYS[_ApyId]= _newValue ; } function setPeriod(uint _PeriodId, uint256 _newValue) public onlyOwner{ periods[_PeriodId]= _newValue ; } /** * stake nft token to this contract. * Note: It calls another internal "_stakeNft" method. See its description. */ function stakeNft(uint256 id, uint256 periodStaking ) external whenNotPaused nonReentrant { _stakeNft(msg.sender, address(this), id, periodStaking); } /** * Transfers `_value` tokens of token type `_id` from `_from` to `_to`. * * Note: when nft staked, apy will changed, should recalculate balance. * update nft balance, nft id, totalNftStaked. * * @param _from The address of the sender. * @param _to The address of the receiver. * @param _id The nft id. */ function _stakeNft( address _from, address _to, uint256 _id, uint256 _periodStaking ) internal { //4 period staking require( _periodStaking > 0 && _periodStaking <= 4, "Not right staking period"); // modify user's nft id array setUserNftIds(_from, _id, _now(),_periodStaking ); totalNftStaked = totalNftStaked.add(1); // transfer nft token to this contract nftContract.safeTransferFrom(_from, _to, _id); // send event emit NftStaked(_from, _id, _now()); } /** * Unstake nft token from this contract. * * Note: It calls another internal "_unstakeNft" method. See its description. * * @param id The nft id. */ function unstakeNft( uint256 id ) external whenNotPaused nonReentrant { _unstakeNft(id); } /** * Unstake nft token with sufficient balance. * * Note: when nft unstaked, apy will changed, should recalculate balance. * update nft balance, nft id and totalNftStaked. * * @param _id The nft id. */ function _unstakeNft( uint256 _id ) internal { // recalculate balance of umi token recalculateBalance(msg.sender, _id); // uint256 nftBalance = nftBalancesStacked[msg.sender]; require( getUserNftIdsLength(msg.sender) > 0, "insufficient balance for unstake" ); // reduce total nft amount totalNftStaked = totalNftStaked.sub(1); // remove nft id from array removeUserNftId(_id); // transfer nft token from this contract nftContract.safeTransferFrom( address(this), msg.sender, _id ); // //withdraw reward too require( rewardToken.transfer(msg.sender, balances[msg.sender]), "claim: transfer failed" ); tokenReceived[msg.sender] = tokenReceived[msg.sender].add(balances[msg.sender]); // send event emit NftUnstaked(msg.sender, _id, _now()); } /** * Withdraws the interest only of user, and updates the stake date, balance and etc.. */ function claimRewardById(uint256 _id) external whenNotPaused nonReentrant { require( getUserNftIdsLength(msg.sender) >= 0 , "No Nts Stocked"); require(totalFunding>0 , "No enough tokens"); // calculate total balance with interest recalculateBalance(msg.sender, _id); //remove the beginning reward uint256 balance = balances[msg.sender]; require(balance > 0, "balance should more than 0"); uint256 claimTimestamp = _now(); // transfer interest to user require( rewardToken.transfer(msg.sender, balance), "claim: transfer failed" ); //amount of token recieved tokenReceived[msg.sender] = tokenReceived[msg.sender].add(balances[msg.sender]); balances[msg.sender]=0; // send claim event emit Claimed(msg.sender, balance, claimTimestamp); } /** * Recalculate user's balance. * * Note: when should recalculate * case 1: unstake nft * case 2: claim reward */ function recalculateBalance(address _from, uint256 _id) internal { // calculate total balance with interest (uint256 totalWithInterest, uint256 timePassed) = calculateRewardsAndTimePassed(_from, _id); require( timePassed >= 0, "NFT and reward unlocked after lock time " ); balances[_from] = balances[_from].add(totalWithInterest); } /* * periodtype =1 - 45days lock * periodtype =2 - 30days * periodtype =3 -15days * periodtype =4 - 7days */ //check if he can withdraw a token he didn't inserted function calculateRewardsAndTimePassed(address _user, uint256 _id) internal returns (uint256, uint256) { NftSet storage nftSet = userNftIds[_user]; uint256[] storage ids = nftSet.ids; uint256[] storage stakingStartTime = nftSet.nftTimes; uint256[] storage stakingPeriod = nftSet.nftPeriodStaking; require(isNftIdExist(_user,_id),"nft is not staked"); uint256 stakeDate ; uint256 periodtype; // find nftId index for (uint256 i = 0; i < ids.length; i++) { if (ids[i] == _id) { stakeDate = stakingStartTime[i] ; periodtype = stakingPeriod[i] ; //reset time for getting reward stakingStartTime[i] = _now(); } } //period of staking uint256 period = periods[periodtype] ; uint256 timePassed = _now().sub(stakeDate); if (timePassed < period) { // if timePassed less than one day, rewards will be 0 return (0, timePassed); } //check if royal or normal cub uint reward = nftdailyrewards[_id]>0 ? nftdailyrewards[_id] : 10 ; reward = reward*10**18 ; uint256 _days = timePassed.div(period); uint256 totalWithInterest = _days.mul(APYS[periodtype]).mul(reward).div(100); return (totalWithInterest, timePassed); } /** * Get umi token balance by address. * @param addr The address of the account that needs to check the balance. * @return Return balance of umi token. */ function getTokenBalance(address addr) public view returns (uint256) { return rewardToken.balanceOf(addr); } /** * Get umi token balance for contract. * @return Return balance of umi token. */ function getStakingBalance() public view returns (uint256) { return rewardToken.balanceOf(address(this)); } /** * Get nft balance by user address and nft id. * * @param user The address of user. */ function getNftBalance(address user) public view returns (uint256) { return nftContract.balanceOf(user); } /** * Get user's nft ids array. * @param user The address of user. */ function getUserNftIds(address user) public view returns (uint256[] memory,uint256[] memory, uint256[] memory) { return (userNftIds[user].ids, userNftIds[user].nftTimes , userNftIds[user].nftPeriodStaking); //nft period ; } /** * Get length of user's nft id array. * @param user The address of user. */ function getUserNftIdsLength(address user) public view returns (uint256) { return userNftIds[user].ids.length; } /** * Check if nft id exist. * @param user The address of user. * @param nftId The nft id of user. */ function isNftIdExist(address user, uint256 nftId) public view returns (bool) { NftSet storage nftSet = userNftIds[user]; mapping(uint256 => bool) storage isIn = nftSet.isIn; return isIn[nftId]; } /** * Set user's nft id. * * Note: when nft id donot exist, the nft id will be added to ids array, and the idIn flag will be setted true; * otherwise do nothing. * * @param user The address of user. * @param nftId The nft id of user. */ function setUserNftIds(address user, uint256 nftId, uint256 stakeTime , uint256 period) internal { NftSet storage nftSet = userNftIds[user]; uint256[] storage ids = nftSet.ids; uint256[] storage stakingStartTime = nftSet.nftTimes; uint256[] storage stakingPeriod = nftSet.nftPeriodStaking; mapping(uint256 => bool) storage isIn = nftSet.isIn; if (!isIn[nftId]) { ids.push(nftId); stakingStartTime.push(stakeTime); stakingPeriod.push(period); isIn[nftId] = true; } } /** * Remove nft id of user. * * Note: when user's nft id amount=0, remove it from nft ids array, and set flag=false */ function removeUserNftId(uint256 nftId) internal { NftSet storage nftSet = userNftIds[msg.sender]; uint256[] storage ids = nftSet.ids; uint256[] storage stakingStartTime = nftSet.nftTimes; uint256[] storage stakingPeriod = nftSet.nftPeriodStaking; mapping(uint256 => bool) storage isIn = nftSet.isIn; require(ids.length > 0, "remove user nft ids, ids length must > 0"); // find nftId index for (uint256 i = 0; i < ids.length; i++) { if (ids[i] == nftId) { ids[i] = ids[ids.length - 1]; stakingStartTime[i] = stakingStartTime[ids.length - 1 ] ; stakingPeriod[i] = stakingPeriod[ids.length - 1 ] ; isIn[nftId] = false; ids.pop(); stakingStartTime.pop(); stakingPeriod.pop(); } } } /** * @return Returns current timestamp. */ function _now() internal view returns (uint256) { return block.timestamp; } function initRewards() internal onlyOwner { nftdailyrewards[2]=50; nftdailyrewards[60]=50; nftdailyrewards[249]=50; nftdailyrewards[350]=50; nftdailyrewards[366]=50; nftdailyrewards[556]=50; nftdailyrewards[577]=50; nftdailyrewards[584]=50; nftdailyrewards[618]=50; nftdailyrewards[731]=50; nftdailyrewards[793]=50; nftdailyrewards[969]=50; nftdailyrewards[1443]=50; nftdailyrewards[1669]=50; nftdailyrewards[1720]=50; nftdailyrewards[1858]=50; nftdailyrewards[1887]=50; nftdailyrewards[2100]=50; nftdailyrewards[2527]=50; nftdailyrewards[2881]=50; nftdailyrewards[3016]=50; nftdailyrewards[3323]=50; nftdailyrewards[3398]=50; nftdailyrewards[3412]=50; nftdailyrewards[3446]=50; nftdailyrewards[3492]=50; nftdailyrewards[3533]=50; nftdailyrewards[3552]=50; nftdailyrewards[3662]=50; nftdailyrewards[3687]=50; nftdailyrewards[3735]=50; nftdailyrewards[3864]=50; nftdailyrewards[3907]=50; nftdailyrewards[3925]=50; nftdailyrewards[3932]=50; nftdailyrewards[4017]=50; nftdailyrewards[4085]=50; nftdailyrewards[4130]=50; nftdailyrewards[4201]=50; nftdailyrewards[4404]=50; } }
Get umi token balance by address. addr The address of the account that needs to check the balance. return Return balance of umi token./
function getTokenBalance(address addr) public view returns (uint256) { return rewardToken.balanceOf(addr); }
12,163,144
// TODO: RAY is written in solidity 0.4, we are using 0.5 is it a problem? pragma solidity >=0.5.0 <0.6.0; // external dependencies import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; // internal dependencies import "./interfaces/ray/IRAY.sol"; import "./interfaces/ray/IRAYStorage.sol"; contract RAYIntegration is Initializable, ERC721Holder { /*************** VARIABLE DECLARATIONS **************/ // RAY smart contracts used, these id's can be used to identify them dynamically bytes32 internal ADMIN_CONTRACT; bytes32 internal PORTFOLIO_MANAGER_CONTRACT; bytes32 internal PAYER_CONTRACT; bytes32 internal RAY_TOKEN_CONTRACT; bytes32 internal NAV_CALCULATOR_CONTRACT; bytes4 internal ERC721_RECEIVER_STANDARD; address internal NULL_ADDRESS; IRAYStorage public rayStorage; // map the 'true' owners of the RAY tokens owned by this contract mapping(bytes32 => address payable) public rayTokens; mapping(address => bytes32[]) private reverseRayTokens; event InvestmentRAY(bytes32 portfolioId, address beneficiary, uint256 value, bytes32 rayTokenId); event DepositRAY(bytes32 rayTokenId, uint256 value, address beneficiary); event RedeemRAY(bytes32 rayTokenId, uint256 value, address beneficiary); event FundsTransferRAY(address tokenAddress, address from, address beneficiary, uint256 value); /*************** MODIFIER DECLARATIONS **************/ /// @dev A modifier that verifies either the msg.sender == our Payer contract /// and then the original caller is passed as a parameter (so check the original caller) /// since we trust Payer. Else msg.sender must be the true owner of the token. /// /// This functionality enables paying for users transactions when interacting /// with RAY. /// /// origCaller is the address that signed the transaction that went through Payer modifier onlyTokenOwner(bytes32 tokenId, address origCaller) { if (msg.sender == rayStorage.getContractAddress(PAYER_CONTRACT)) { require(rayTokens[tokenId] == origCaller, "#RAYIntegration onlyTokenOwner modifier: The original caller is not the owner of the token"); } else { require(rayTokens[tokenId] == msg.sender, "#RAYIntegration onlyTokenOwner modifier: The caller is not the owner of the token"); } _; } /////////////////////// FUNCTION DECLARATIONS BEGIN /////////////////////// /******************* PUBLIC FUNCTIONS *******************/ /// @notice Init contract by referencing the Eternal storage contract of RAY /// /// @param _rayStorage - The address of the RAY storage contract function init(address _rayStorage) public initializer { rayStorage = IRAYStorage(_rayStorage); // constants ADMIN_CONTRACT = keccak256("AdminContract"); PORTFOLIO_MANAGER_CONTRACT = keccak256("PortfolioManagerContract"); PAYER_CONTRACT = keccak256("PayerContract"); RAY_TOKEN_CONTRACT = keccak256("RAYTokenContract"); NAV_CALCULATOR_CONTRACT = keccak256("NAVCalculatorContract"); ERC721_RECEIVER_STANDARD = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); NULL_ADDRESS = address(0); } function genPortfolioId(string memory portfolioDescription) public pure returns (bytes32) { return keccak256(abi.encodePacked(portfolioDescription)); } function getRayTokens(address wallet) public view returns (bytes32[] memory) { return reverseRayTokens[wallet]; } function getTokenOwner(bytes32 tokenId) external view returns (address) { return rayTokens[tokenId]; } /// @notice Fallback function to receive Ether /// /// @dev Required to receive Ether from PortfolioManager upon withdraws function() external payable {} /** --------------------- RAY ENTRYPOINTS --------------------- **/ /// @notice Allows users to deposit ETH or accepted ERC20's to this contract and /// used as capital. In return they receive an ERC-721 'RAY' token. /// /// @param portfolioId - The portfolio id /// @param beneficiary - The address that will own the position /// @param value - The amount to be deposited denominated in the smallest units /// in-kind. Ex. For USDC, to deposit 1 USDC, value = 1000000 /// /// @return The unique token id of the new RAY token position function mint(bytes32 portfolioId, address payable beneficiary, uint value) external payable returns (bytes32) { address rayContract = rayStorage.getContractAddress(PORTFOLIO_MANAGER_CONTRACT); uint payableValue = verifyValue(portfolioId, beneficiary, value, rayContract); // this contract will own the minted RAY bytes32 rayTokenId = IRAY(rayContract).mint.value(payableValue)(portfolioId, address(this), value); // payable value can be 0 // map RAY's to their true owners rayTokens[rayTokenId] = beneficiary; reverseRayTokens[beneficiary].push(rayTokenId); emit InvestmentRAY(portfolioId, beneficiary, value, rayTokenId); return rayTokenId; } /// @notice Adds capital to an existing RAY token, this doesn't restrict who /// adds. Addresses besides the owner can add value to the position. /// /// @dev The value added must be in the same underlying asset as the position. /// /// @param rayTokenId - The unique id of the RAY token /// @param value - The amount to be deposited denominated in the smallest units /// in-kind. Ex. For USDC, to deposit 1 USDC, value = 1000000 function deposit(bytes32 rayTokenId, uint value) external payable { bytes32 portfolioId = rayStorage.getTokenKey(rayTokenId); address rayContract = rayStorage.getContractAddress(PORTFOLIO_MANAGER_CONTRACT); uint payableValue = verifyValue(portfolioId, msg.sender, value, rayContract); IRAY(rayContract).deposit.value(payableValue)(rayTokenId, value); emit DepositRAY(rayTokenId, value, rayTokens[rayTokenId]); } /// @notice Withdraw value from a RAY token /// /// @dev Caller must be the 'true' owner of the token or RAY's GasFunder (Payer) contract /// /// @param rayTokenId - The id of the position /// @param valueToWithdraw - The value to withdraw /// @param originalCaller - Unimportant unless Payer is the msg.sender, tells /// us who signed the original message. function redeem(bytes32 rayTokenId, uint valueToWithdraw, address originalCaller) internal returns (bytes32, uint256) { bytes32 portfolioId = rayStorage.getTokenKey(rayTokenId); address rayContract = rayStorage.getContractAddress(PORTFOLIO_MANAGER_CONTRACT); uint valueAfterFee = IRAY(rayContract).redeem(rayTokenId, valueToWithdraw, originalCaller); emit RedeemRAY(rayTokenId, valueAfterFee, rayTokens[rayTokenId]); return (portfolioId, valueAfterFee); } /// @notice Withdraw value from a RAY token /// /// @dev Caller must be the 'true' owner of the token or RAY's GasFunder (Payer) contract /// /// @param rayTokenId - The id of the position /// @param valueToWithdraw - The value to withdraw /// @param originalCaller - Unimportant unless Payer is the msg.sender, tells /// us who signed the original message. function redeemAndWithdraw(bytes32 rayTokenId, uint valueToWithdraw, address originalCaller) public { bytes32 portfolioId; uint256 valueAfterFee; (portfolioId, valueAfterFee) = redeem(rayTokenId, valueToWithdraw, originalCaller); address payable beneficiary = rayTokens[rayTokenId]; transferFunds(portfolioId, beneficiary, valueAfterFee); } /// @notice Gets a RAY tokens current value /// /// @param rayTokenId - The unique token id of the RAY /// /// @return Value of the token function getTokenValue(bytes32 rayTokenId) public view returns (uint) { uint tokenValue; uint pricePerShare; bytes32 portfolioId = rayStorage.getTokenKey(rayTokenId); (tokenValue, pricePerShare) = IRAY(rayStorage.getContractAddress(NAV_CALCULATOR_CONTRACT)).getTokenValue(portfolioId, rayTokenId); return tokenValue; } /************************ INTERNAL FUNCTIONS **********************/ /// @notice Verifies the funds have been credited to this contract and then /// returns the 'payable' value - the amount of ETH to be forwarded. /// /// @param portfolioId - The portfolioId the RAY being minted or deposited is /// associated with /// @param funder - The address funding the transaction /// @param inputValue - The value input to the function parameter /// @param rayContract - The address of the PortfolioManager /// /// @return The 'payable' value to be forwarded to the PortfolioManager function verifyValue( bytes32 portfolioId, address funder, uint inputValue, address rayContract ) internal returns(uint) { address principalAddress = rayStorage.getPrincipalAddress(portfolioId); if (rayStorage.getIsERC20(principalAddress)) { require(IERC20(principalAddress).transferFrom(funder, address(this), inputValue), "#RAYIntegration verifyValue(): Transfer of ERC20 Token failed"); // could one time max approve the ray contract (or everytime it upgrades and changes addresses) require(IERC20(principalAddress).approve(rayContract, inputValue), "#RAYIntegration verifyValue(): Approval of ERC20 Token failed"); return 0; } else { require(inputValue == msg.value, "#RAYIntegration verifyValue(): ETH value sent does not match input value"); return inputValue; } } /// @notice Used to transfer ETH or ERC20's /// /// @param portfolioId - The portfolio id, used to get the coin associated /// @param beneficiary - The address to send funds to - is untrusted /// @param value - The value to send in-kind in smallest units function transferFunds( bytes32 portfolioId, address payable beneficiary, uint value ) internal { address principalAddress = rayStorage.getPrincipalAddress(portfolioId); if (rayStorage.getIsERC20(principalAddress)) { require(IERC20(principalAddress).transfer(beneficiary, value), "#RAYIntegration transferFunds(): Transfer of ERC20 token failed"); emit FundsTransferRAY(principalAddress, address(this), beneficiary, value); } else { beneficiary.transfer(value); emit FundsTransferRAY(address(0), address(this), beneficiary, value); } } function getSenderTokens() external view returns (address [] memory tokens, uint[] memory balances) { bytes32[] memory tokensId = reverseRayTokens[msg.sender]; tokens = new address [](tokensId.length); balances = new uint[](tokensId.length); for (uint i = 0; i < tokensId.length; i++) { bytes32 portfolioId = rayStorage.getTokenKey(tokensId[i]); uint tokenValue; uint pricePerShare; (tokenValue, pricePerShare) = IRAY(rayStorage.getContractAddress(NAV_CALCULATOR_CONTRACT)).getTokenValue(portfolioId, tokensId[i]); tokens[i] = rayStorage.getPrincipalAddress(portfolioId); balances[i] = tokenValue; } } }
Verifies the funds have been credited to this contract and then returns the 'payable' value - the amount of ETH to be forwarded. portfolioId - The portfolioId the RAY being minted or deposited is associated with funder - The address funding the transaction inputValue - The value input to the function parameter rayContract - The address of the PortfolioManager return The 'payable' value to be forwarded to the PortfolioManager could one time max approve the ray contract (or everytime it upgrades and changes addresses)
function verifyValue( bytes32 portfolioId, address funder, uint inputValue, address rayContract ) internal returns(uint) { address principalAddress = rayStorage.getPrincipalAddress(portfolioId); if (rayStorage.getIsERC20(principalAddress)) { require(IERC20(principalAddress).transferFrom(funder, address(this), inputValue), "#RAYIntegration verifyValue(): Transfer of ERC20 Token failed"); require(IERC20(principalAddress).approve(rayContract, inputValue), "#RAYIntegration verifyValue(): Approval of ERC20 Token failed"); return 0; require(inputValue == msg.value, "#RAYIntegration verifyValue(): ETH value sent does not match input value"); return inputValue; } }
6,488,460
./full_match/80001/0x4a9da3931c7d03E14061220F757b1E9BF8563c15/sources/project_/contracts/libs/MintSignatureVerifier.sol
Check if the signature has been used before
function checkMintSignature(bytes32 uid) public view returns (bool) { if (usedSignatures[uid]) { return false; } return true; }
864,376
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/lib/ConsiderationErrors.sol
Reverts execution with a "NoReentrantCalls" error message./
function _revertNoReentrantCalls() pure { assembly { mstore(0, NoReentrantCalls_error_selector) revert(Error_selector_offset, NoReentrantCalls_error_length) } }
4,301,451
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import './Base64.sol'; import './Utils.sol'; contract CryptoDuckies is ERC721Enumerable, Ownable { bytes[119] private _assets; uint256[1250] private _tokensData; bool public canMigrate; bool public isSealed; uint256 private constant ERC1155_ADDRESS0 = 0xa4a236d97a2afa4b37693e5df8aa5afc68c42cd1000000000000000000000001; uint256 private constant ERC1155_ADDRESS1 = 0x877ac19ddc87391373cc71e25ee8e6e14f237ae5000000000000000000000001; address private constant OPENSEA_OPENSTORE = address(0x495f947276749Ce646f68AC8c248420045cb7b5e); address private constant OPENSEA_PROXYREGISTRY = address(0xa5409ec958C83C3f309868babACA7c86DCB077c1); address private constant BURN = address(0x000000000000000000000000000000000000dEaD); constructor() ERC721("CryptoDuckies", "DUCKIE") {} modifier validTokenId(uint256 tokenId) { require(tokenId >= 1 && tokenId <= 5000, "Not a valid token number"); _; } modifier migrating() { require(canMigrate, "Migration has not started"); _; } modifier unsealed() { require(!isSealed, "Contract is sealed"); _; } function setAsset(uint256 index, bytes calldata encodedAsset) external onlyOwner unsealed { unchecked { _assets[index-1] = encodedAsset; } } function setTokens(uint256 index, uint256[] calldata encodedTokens) external onlyOwner unsealed { unchecked { uint length = encodedTokens.length; for (uint i=0; i<length; i++) { _tokensData[index] = encodedTokens[i]; index++; } } } function seal() external onlyOwner { isSealed = true; } function flipMigration() external onlyOwner { canMigrate = !canMigrate; } function _tokenData(uint256 tokenId) private view validTokenId(tokenId) returns (uint256 tokenData) { unchecked { uint256 index = tokenId-1; tokenData = _tokensData[index >> 2] >> (((index & 3) << 6)+15); } } function _traits(uint256 tokenData) private view returns (string memory text) { bytes memory buffer = new bytes(320); // create a big enough buffer to store the maximum amount of traits assembly { mstore(buffer, 0) // set initial length to 0 } unchecked { bytes32 trait_start = bytes32('[{"trait_type":"'); for (uint j = 0; j < 7; j++) { uint256 assetIndex = tokenData & 0x7f; if (assetIndex == 0) { break; } bytes storage asset = _assets[assetIndex-1]; uint256 trait; assembly { trait := sload(asset.slot) if eq(and(trait, 1), 1) { mstore(0, asset.slot) trait := sload(keccak256(0, 32)) } } trait <<= 8; // first byte is offset to image data uint256 strLength = trait >> 248; if (strLength > 0) { Utils.appendString(buffer, trait_start, 16); trait_start = bytes32(',{"trait_type":"'); // append trait type trait <<= 8; Utils.appendString(buffer, trait, strLength); trait <<= strLength << 3; Utils.appendString(buffer, bytes32('","value":"'), 11); // append trait value strLength = trait >> 248; trait <<= 8; Utils.appendString(buffer, trait, strLength); Utils.appendString(buffer, bytes32('"}'), 2); } tokenData >>= 7; } Utils.appendString(buffer, bytes32(']'), 1); } return string(buffer); } function _imagePixels(uint256 tokenData, bool premultipliedAlpha) private view returns (bytes memory pixels) { pixels = new bytes(2304); unchecked { bool hasAlpha = false; for (uint j = 0; j < 6; j++) { tokenData >>= 7; uint256 assetIndex = tokenData & 0x7f; if (assetIndex == 0) { break; } hasAlpha = Utils.blend(pixels, _assets[assetIndex-1]) || hasAlpha; } if (hasAlpha && !premultipliedAlpha) { Utils.unpremultiplyingAlpha(pixels); } } } function _backgroundColor(uint256 tokenData) private view returns (uint32) { uint256 assetIndex = tokenData & 0x7f; bytes storage asset = _assets[assetIndex-1]; uint256 assetData; assembly { assetData := sload(asset.slot) // background assets are always contained within one word } uint256 offset = assetData >> 248; return uint32((assetData >> ((28 - offset) << 3)) & 0xffffffff); } function _imageSVG(uint256 tokenData) private view returns (string memory) { bytes memory pixels = _imagePixels(tokenData, true); uint256 bgColor = uint256(_backgroundColor(tokenData)); bytes memory buffer = new bytes(15200); // create a big enough buffer Utils.createSVG(buffer, pixels, 24, 24, bgColor); return string(buffer); } /** * The traits of the Crypto Duckie as a JSON array */ function traits(uint256 tokenId) public view returns (string memory text) { return _traits(_tokenData(tokenId)); } /** * The Crypto Duckie as a 24x24x4 sized byte array of RGBA pixel values without the background * Set premultipliedAlpha parameter to true if you want the RGB values to be premultiplied by the alpha value */ function imagePixels(uint256 tokenId, bool premultipliedAlpha) public view returns (bytes memory) { return _imagePixels(_tokenData(tokenId), premultipliedAlpha); } /** * The background color of the Crypto Duckie as RGBA */ function backgroundColor(uint256 tokenId) public view returns (bytes4) { return bytes4(_backgroundColor(_tokenData(tokenId))); } /** * SVG of the Crypto Duckie */ function imageSVG(uint256 tokenId) public view returns (string memory svg) { return _imageSVG(_tokenData(tokenId)); } function tokenURI(uint256 tokenId) public view override returns (string memory) { uint256 tokenData = _tokenData(tokenId); string memory attributes = _traits(tokenData); string memory svg = _imageSVG(tokenData); bytes memory json = abi.encodePacked('{"name":"Duckie #', Utils.toString(tokenId),'", "attributes":', attributes,', "image": "data:image/svg+xml;base64,', Base64.encode(bytes(svg)), '"}'); return string(abi.encodePacked('data:application/json;base64,', Base64.encode(json))); } function toERC1155TokenId(uint256 tokenId) public view validTokenId(tokenId) returns (uint256 tokenIdERC1155) { unchecked { uint256 index = tokenId-1; uint256 tokenData = _tokensData[index >> 2] >> ((index & 3) << 6); tokenIdERC1155 = ((tokenData & 0x1fff) << 40) | ((tokenData & 0x2000) == 0 ? ERC1155_ADDRESS0 : ERC1155_ADDRESS1); } } function emergencyMint(uint256 tokenId) external onlyOwner validTokenId(tokenId) { _mint(msg.sender, tokenId); } function migrate(uint256 tokenId) external migrating { uint256 tokenIdERC1155 = toERC1155TokenId(tokenId); IERC1155(OPENSEA_OPENSTORE).safeTransferFrom(msg.sender, BURN, tokenIdERC1155, 1, ""); _mint(msg.sender, tokenId); } function migrateFlock(uint256[] calldata tokenIds) external migrating { uint256 length = tokenIds.length; uint256[] memory tokenIdsERC1155 = new uint256[](length); uint256[] memory amounts = new uint256[](length); for (uint256 i=0; i<length; i++) { uint256 tokenId = tokenIds[i]; tokenIdsERC1155[i] = toERC1155TokenId(tokenId); _mint(msg.sender, tokenId); amounts[i] = 1; } IERC1155(OPENSEA_OPENSTORE).safeBatchTransferFrom(msg.sender, BURN, tokenIdsERC1155, amounts, ""); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { return super.isApprovedForAll(owner, operator) || address(ProxyRegistry(OPENSEA_PROXYREGISTRY).proxies(owner)) == operator; } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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 "../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; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ''; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF) ) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Util /// @notice Utility functions for On-Chain pixel NFTs /// @author ponky library Utils { /// @notice divides image’s RGB values by its alpha values function unpremultiplyingAlpha(bytes memory pixels) internal pure { unchecked { uint pi = 0; assembly { pi := add(pi, pixels) } uint length = pixels.length; for (uint i; i<length; i+=32) { // pixels is assumed to be 8 pixels aligned pi += 32; uint256 p; assembly { p := mload(pi) } if (p != 0) { uint pixelShift = 256; do { pixelShift -= 32; uint256 color = (p >> pixelShift) & 0xffffffff; uint256 alpha = color & 0xff; if (alpha != 0 && alpha != 255) { color = (((((color >> 24) & 0xff) * 255) / alpha) << 24) | (((((color >> 16) & 0xff) * 255) / alpha) << 16) | (((((color >> 8) & 0xff) * 255) / alpha) << 8) | alpha; p = (p & ~(0xffffffff << pixelShift)) | (color << pixelShift); } } while (pixelShift > 0); assembly { mstore(pi, p) } } } } } /// @notice blends the compressed image of an asset onto a 24x24 pixel image, RGB values are premultiplied by the alpha value function blend(bytes memory pixels, bytes memory asset) internal pure returns (bool hasAlpha) { unchecked { uint offset = uint(uint8(asset[0])); // offset to image data uint pi; { uint left = uint(uint8(asset[offset])); uint top = uint(uint8(asset[offset+1])); pi = (top * 24 + left) * 4; } assembly { pi := add(pi, pixels) } hasAlpha = (uint8(asset[offset+3]) & 1) != 0; uint ci = 0; uint ii = 0; uint count = 0; uint length = asset.length * 2; for (uint ai=(offset + 4 + uint(uint8(asset[offset+2])) * 4) * 2; ai<length; ai++) { uint i; if ((ai & 1) != 0) { i = ii & 0xF; if (i == 0xf) { ai++; ii = uint(uint8(asset[ai >> 1])); count += (ii >> 4) + 3; continue; } } else { ii = uint(uint8(asset[ai >> 1])); i = ii >> 4; if (i == 0xf) { ai++; count += (ii & 0xf) + 3; continue; } } if (ci != i) { if (ci == 0) { pi += count * 4; } else { ci = offset + ci * 4 + 4; if (hasAlpha) { assembly { let color := and(mload(add(asset, ci)), 0xffffffff) let a := sub(256, and(color, 0xff)) for {} gt(count, 0) {count := sub(count, 1)} { pi := add(pi, 4) let p := mload(pi) p := or(and(p, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000), add(color, or(and(shr(8, mul(and(p, 0xff00ff00), a)), 0xff00ff00), and(shr(8, mul(and(p, 0xff00ff), a)), 0xff00ff)))) mstore(pi, p) } } } else { assembly { let color := and(mload(add(asset, ci)), 0xffffffff) for {} gt(count, 0) {count := sub(count, 1)} { pi := add(pi, 4) let p := mload(pi) p := or(and(p, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000), color) mstore(pi, p) } } } } ci = i; count = 0; } count++; } } } /// @notice Append strLength bytes of the left-aligned str to buffer function appendString(bytes memory buffer, uint256 str, uint256 strLength) internal pure { uint256 length = buffer.length; assembly { let shift := shl(3, sub(32, strLength)) let strc := shl(shift, shr(shift, str)) let bufferptr := add(buffer, add(0x20, length)) mstore(bufferptr, strc) mstore(buffer, add(length, strLength)) } } function appendString(bytes memory buffer, bytes32 str, uint256 strLength) internal pure { appendString(buffer, uint256(str), strLength); } /// @notice append astring to buffer function appendString(bytes memory buffer, string memory str) internal pure { uint256 strLength = bytes(str).length; uint256 length = buffer.length; assembly { let strptr := add(str, 0x20) let bufferptr := add(buffer, add(0x20, length)) let l := strLength for {} gt(l, 31) { l := sub(l, 32) } { mstore(bufferptr, mload(strptr)) strptr := add(strptr, 32) bufferptr := add(bufferptr, 32) } if gt(l, 0) { let shift := shl(3, sub(32, l)) let strc := shl(shift, shr(shift, mload(strptr))) mstore(bufferptr, strc) } mstore(buffer, add(length, strLength)) } } bytes16 private constant HEX_SYMBOLS = "0123456789abcdef"; /// @notice append an RGBA color as a hex string to buffer function appendColor(bytes memory buffer, uint256 color) internal pure { uint256 str = 0; unchecked { uint colorShift = 32; do { colorShift -= 4; str |= uint256(uint8(HEX_SYMBOLS[(color >> colorShift) & 0xf])) << (192 + (colorShift<<1)); } while (colorShift > 0); } appendString(buffer, str, 8); } /// @notice append a number as a decimal value string to buffer, number must be within 32 digits function appendNumber(bytes memory buffer, uint256 number) internal pure { uint256 str = 0; uint256 strLength = 0; unchecked { do { uint256 digit = (number % 10) + 48; str = (str >> 8) | (digit << 248); number /= 10; strLength++; } while (number > 0); } appendString(buffer, str, strLength); } /// @notice convert number to a decimal value string, number must be within 32 digits function toString(uint256 number) internal pure returns (string memory) { bytes memory buffer = new bytes(32); assembly { mstore(buffer, 0) // set initial length to 0 } appendNumber(buffer, number); return string(buffer); } /// @notice blends a premultiplied RGBA color with an RGBA background color function blendColor(uint256 colorBackground, uint256 colorBlend) internal pure returns (uint256) { unchecked { uint256 ai = 255 - (colorBlend & 0xff); return colorBlend + ( (((((colorBackground >> 24) & 0xff) * ai) / 255) << 24) | (((((colorBackground >> 16) & 0xff) * ai) / 255) << 16) | (((((colorBackground >> 8) & 0xff) * ai) / 255) << 8) | (((((colorBackground ) & 0xff) * ai) / 255) )); } } /// @notice append a colored SVG rect shape to the buffer function appendSVGRect(bytes memory buffer, uint256 x, uint256 y, uint256 width, uint256 height, uint256 color) internal pure { appendString(buffer, bytes32('<rect x="'), 9); appendNumber(buffer, x); appendString(buffer, bytes32('" y="'), 5); appendNumber(buffer, y); appendString(buffer, bytes32('" width="'), 9); appendNumber(buffer, width); appendString(buffer, bytes32('" height="'), 10); appendNumber(buffer, height); appendString(buffer, bytes32('" shape-rendering="crispEdges'), 29); appendString(buffer, bytes32('" fill="#'), 9); appendColor(buffer, color); appendString(buffer, bytes32('"/>'), 3); } /// @notice convert RGBA pixel data to a pixelated SVG and store it in buffer, buffer needs to be allocated with enough space /// @dev macOS has artifacts when rendering adjacent translucent rectangles so tranlucent pixels are blended with the background color function createSVG(bytes memory buffer, bytes memory pixels, uint256 width, uint256 height, uint256 backgroundColor) internal pure { assembly { mstore(buffer, 0) // set initial length to 0 } unchecked { Utils.appendString(buffer, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 24 24">'); if (backgroundColor != 0) { Utils.appendSVGRect(buffer, 0, 0, width, height, backgroundColor); } uint pi = 0; assembly { pi := add(pi, pixels) } for (uint y=0; y<height; y++) { uint w = 0; uint l = 0; uint prevColor = 0; for (uint x=0; x<width; ) { pi += 32; uint256 p; assembly { p := mload(pi) } uint pixelShift = 256; do { pixelShift -= 32; uint256 color = (p >> pixelShift) & 0xffffffff; if (color != prevColor) { if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); w = 0; } prevColor = color; l = x; } if (color != 0) { w++; } x++; } while (pixelShift > 0); } if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); } } Utils.appendString(buffer, bytes32('</svg>'), 6); } } } // 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; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @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); }
convert RGBA pixel data to a pixelated SVG and store it in buffer, buffer needs to be allocated with enough space macOS has artifacts when rendering adjacent translucent rectangles so tranlucent pixels are blended with the background color
function createSVG(bytes memory buffer, bytes memory pixels, uint256 width, uint256 height, uint256 backgroundColor) internal pure { assembly { } unchecked { if (backgroundColor != 0) { Utils.appendSVGRect(buffer, 0, 0, width, height, backgroundColor); } uint pi = 0; assembly { pi := add(pi, pixels) } for (uint y=0; y<height; y++) { uint w = 0; uint l = 0; uint prevColor = 0; for (uint x=0; x<width; ) { pi += 32; uint256 p; assembly { p := mload(pi) } uint pixelShift = 256; do { pixelShift -= 32; uint256 color = (p >> pixelShift) & 0xffffffff; if (color != prevColor) { if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); w = 0; } prevColor = color; l = x; } if (color != 0) { w++; } x++; } while (pixelShift > 0); } if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); } } Utils.appendString(buffer, bytes32('</svg>'), 6); } unchecked { if (backgroundColor != 0) { Utils.appendSVGRect(buffer, 0, 0, width, height, backgroundColor); } uint pi = 0; assembly { pi := add(pi, pixels) } for (uint y=0; y<height; y++) { uint w = 0; uint l = 0; uint prevColor = 0; for (uint x=0; x<width; ) { pi += 32; uint256 p; assembly { p := mload(pi) } uint pixelShift = 256; do { pixelShift -= 32; uint256 color = (p >> pixelShift) & 0xffffffff; if (color != prevColor) { if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); w = 0; } prevColor = color; l = x; } if (color != 0) { w++; } x++; } while (pixelShift > 0); } if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); } } Utils.appendString(buffer, bytes32('</svg>'), 6); } unchecked { if (backgroundColor != 0) { Utils.appendSVGRect(buffer, 0, 0, width, height, backgroundColor); } uint pi = 0; assembly { pi := add(pi, pixels) } for (uint y=0; y<height; y++) { uint w = 0; uint l = 0; uint prevColor = 0; for (uint x=0; x<width; ) { pi += 32; uint256 p; assembly { p := mload(pi) } uint pixelShift = 256; do { pixelShift -= 32; uint256 color = (p >> pixelShift) & 0xffffffff; if (color != prevColor) { if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); w = 0; } prevColor = color; l = x; } if (color != 0) { w++; } x++; } while (pixelShift > 0); } if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); } } Utils.appendString(buffer, bytes32('</svg>'), 6); } unchecked { if (backgroundColor != 0) { Utils.appendSVGRect(buffer, 0, 0, width, height, backgroundColor); } uint pi = 0; assembly { pi := add(pi, pixels) } for (uint y=0; y<height; y++) { uint w = 0; uint l = 0; uint prevColor = 0; for (uint x=0; x<width; ) { pi += 32; uint256 p; assembly { p := mload(pi) } uint pixelShift = 256; do { pixelShift -= 32; uint256 color = (p >> pixelShift) & 0xffffffff; if (color != prevColor) { if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); w = 0; } prevColor = color; l = x; } if (color != 0) { w++; } x++; } while (pixelShift > 0); } if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); } } Utils.appendString(buffer, bytes32('</svg>'), 6); } unchecked { if (backgroundColor != 0) { Utils.appendSVGRect(buffer, 0, 0, width, height, backgroundColor); } uint pi = 0; assembly { pi := add(pi, pixels) } for (uint y=0; y<height; y++) { uint w = 0; uint l = 0; uint prevColor = 0; for (uint x=0; x<width; ) { pi += 32; uint256 p; assembly { p := mload(pi) } uint pixelShift = 256; do { pixelShift -= 32; uint256 color = (p >> pixelShift) & 0xffffffff; if (color != prevColor) { if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); w = 0; } prevColor = color; l = x; } if (color != 0) { w++; } x++; } while (pixelShift > 0); } if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); } } Utils.appendString(buffer, bytes32('</svg>'), 6); } unchecked { if (backgroundColor != 0) { Utils.appendSVGRect(buffer, 0, 0, width, height, backgroundColor); } uint pi = 0; assembly { pi := add(pi, pixels) } for (uint y=0; y<height; y++) { uint w = 0; uint l = 0; uint prevColor = 0; for (uint x=0; x<width; ) { pi += 32; uint256 p; assembly { p := mload(pi) } uint pixelShift = 256; do { pixelShift -= 32; uint256 color = (p >> pixelShift) & 0xffffffff; if (color != prevColor) { if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); w = 0; } prevColor = color; l = x; } if (color != 0) { w++; } x++; } while (pixelShift > 0); } if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); } } Utils.appendString(buffer, bytes32('</svg>'), 6); } unchecked { if (backgroundColor != 0) { Utils.appendSVGRect(buffer, 0, 0, width, height, backgroundColor); } uint pi = 0; assembly { pi := add(pi, pixels) } for (uint y=0; y<height; y++) { uint w = 0; uint l = 0; uint prevColor = 0; for (uint x=0; x<width; ) { pi += 32; uint256 p; assembly { p := mload(pi) } uint pixelShift = 256; do { pixelShift -= 32; uint256 color = (p >> pixelShift) & 0xffffffff; if (color != prevColor) { if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); w = 0; } prevColor = color; l = x; } if (color != 0) { w++; } x++; } while (pixelShift > 0); } if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); } } Utils.appendString(buffer, bytes32('</svg>'), 6); } unchecked { if (backgroundColor != 0) { Utils.appendSVGRect(buffer, 0, 0, width, height, backgroundColor); } uint pi = 0; assembly { pi := add(pi, pixels) } for (uint y=0; y<height; y++) { uint w = 0; uint l = 0; uint prevColor = 0; for (uint x=0; x<width; ) { pi += 32; uint256 p; assembly { p := mload(pi) } uint pixelShift = 256; do { pixelShift -= 32; uint256 color = (p >> pixelShift) & 0xffffffff; if (color != prevColor) { if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); w = 0; } prevColor = color; l = x; } if (color != 0) { w++; } x++; } while (pixelShift > 0); } if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); } } Utils.appendString(buffer, bytes32('</svg>'), 6); } unchecked { if (backgroundColor != 0) { Utils.appendSVGRect(buffer, 0, 0, width, height, backgroundColor); } uint pi = 0; assembly { pi := add(pi, pixels) } for (uint y=0; y<height; y++) { uint w = 0; uint l = 0; uint prevColor = 0; for (uint x=0; x<width; ) { pi += 32; uint256 p; assembly { p := mload(pi) } uint pixelShift = 256; do { pixelShift -= 32; uint256 color = (p >> pixelShift) & 0xffffffff; if (color != prevColor) { if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); w = 0; } prevColor = color; l = x; } if (color != 0) { w++; } x++; } while (pixelShift > 0); } if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); } } Utils.appendString(buffer, bytes32('</svg>'), 6); } unchecked { if (backgroundColor != 0) { Utils.appendSVGRect(buffer, 0, 0, width, height, backgroundColor); } uint pi = 0; assembly { pi := add(pi, pixels) } for (uint y=0; y<height; y++) { uint w = 0; uint l = 0; uint prevColor = 0; for (uint x=0; x<width; ) { pi += 32; uint256 p; assembly { p := mload(pi) } uint pixelShift = 256; do { pixelShift -= 32; uint256 color = (p >> pixelShift) & 0xffffffff; if (color != prevColor) { if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); w = 0; } prevColor = color; l = x; } if (color != 0) { w++; } x++; } while (pixelShift > 0); } if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); } } Utils.appendString(buffer, bytes32('</svg>'), 6); } unchecked { if (backgroundColor != 0) { Utils.appendSVGRect(buffer, 0, 0, width, height, backgroundColor); } uint pi = 0; assembly { pi := add(pi, pixels) } for (uint y=0; y<height; y++) { uint w = 0; uint l = 0; uint prevColor = 0; for (uint x=0; x<width; ) { pi += 32; uint256 p; assembly { p := mload(pi) } uint pixelShift = 256; do { pixelShift -= 32; uint256 color = (p >> pixelShift) & 0xffffffff; if (color != prevColor) { if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); w = 0; } prevColor = color; l = x; } if (color != 0) { w++; } x++; } while (pixelShift > 0); } if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); } } Utils.appendString(buffer, bytes32('</svg>'), 6); } unchecked { if (backgroundColor != 0) { Utils.appendSVGRect(buffer, 0, 0, width, height, backgroundColor); } uint pi = 0; assembly { pi := add(pi, pixels) } for (uint y=0; y<height; y++) { uint w = 0; uint l = 0; uint prevColor = 0; for (uint x=0; x<width; ) { pi += 32; uint256 p; assembly { p := mload(pi) } uint pixelShift = 256; do { pixelShift -= 32; uint256 color = (p >> pixelShift) & 0xffffffff; if (color != prevColor) { if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); w = 0; } prevColor = color; l = x; } if (color != 0) { w++; } x++; } while (pixelShift > 0); } if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); } } Utils.appendString(buffer, bytes32('</svg>'), 6); } unchecked { if (backgroundColor != 0) { Utils.appendSVGRect(buffer, 0, 0, width, height, backgroundColor); } uint pi = 0; assembly { pi := add(pi, pixels) } for (uint y=0; y<height; y++) { uint w = 0; uint l = 0; uint prevColor = 0; for (uint x=0; x<width; ) { pi += 32; uint256 p; assembly { p := mload(pi) } uint pixelShift = 256; do { pixelShift -= 32; uint256 color = (p >> pixelShift) & 0xffffffff; if (color != prevColor) { if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); w = 0; } prevColor = color; l = x; } if (color != 0) { w++; } x++; } while (pixelShift > 0); } if (w > 0) { if ((prevColor & 0xff) != 0xff) { prevColor = blendColor(backgroundColor, prevColor); } Utils.appendSVGRect(buffer, l, y, w, 1, prevColor); } } Utils.appendString(buffer, bytes32('</svg>'), 6); } }
12,693,457