file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
pragma solidity ^0.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; } } /** * @dev This is a library based implementation of the ERC20 token standard. * This library allows all values to be set by interface logic. This includes * the ability to set msg.sender. This allows two distinct advantages: * - Access control logic may be layered without the need to change the * core logic of the ERC20 system in any way. * - Tokens that require administrative action, under some conditions, * may take administrative action on an account, without having to * create fragile backdoors into the transfer logic of the token. This * system makes such administrative priveledge clear, apparent, and * more easily auditable to ensure reasonable limitations of power. */ library ERC20Lib { //////////////////////////////////////////////////////////////////////////// //Imports /** * @dev Prevents underflow and overflow attacks.. */ using SafeMath for uint256; /////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //Events /** * @dev Transfer event emitted in 3 cases; transfers, minting, and burning. * for transfers, all fields set as normal * for minting from is set to address(0) * for burning is set to address(0) */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Specifies an approval being granted from an owner to a spender * for the amount specified. */ event Approval(address indexed owner, address indexed spender, uint256 value); //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //Declarations /** * @dev Struct like representation of ERC20 state vairiables. * this allows the ERC20 logic to become a library under using for syntax */ struct Token{ mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _allowed; uint256 _totalSupply; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //Logic /** * @dev Returns the total supply of the token. */ function totalSupply(Token storage self) internal view returns (uint256) { return self._totalSupply; } /** * @dev Returns the balance of an account. */ function balances(Token storage self, address account) internal view returns (uint256) { return self._balances[account]; } /** * @dev Returns the total allowance from the account to the spender.. */ function allowance(Token storage self, address account, address spender) internal view returns (uint256) { return self._allowed[account][spender]; } /** * @dev Issues an allowance from an account to another. */ function approve(Token storage self, address sender, address spender, uint256 value) internal { require(spender != address(0)); self._allowed[sender][spender] = value; emit Approval(sender, spender, value); } /** * @dev Cause a transfer to occur based on an existing allowance. */ function transferFrom(Token storage self, address sender, address from, address to, uint256 value) internal { require(value <= self._allowed[from][sender]); self._allowed[from][sender] = self._allowed[from][sender].sub(value); transfer(self,from, to, value); } /** * @dev Increase the allowance from one account to another. Prevents * change allowance attack. */ function increaseAllowance(Token storage self, address sender, address spender, uint256 addedValue) internal { require(spender != address(0)); self._allowed[sender][spender] = self._allowed[sender][spender].add(addedValue); emit Approval(sender, spender, self._allowed[sender][spender]); } /** * @dev Decrease the allowance from one account to another. Prevents * the change allowance attack. */ function decreaseAllowance(Token storage self, address sender, address spender, uint256 subtractedValue) internal { require(spender != address(0)); self._allowed[sender][spender] = self._allowed[sender][spender].sub(subtractedValue); emit Approval(sender, spender, self._allowed[sender][spender]); } /** * @dev Transfer tokens from one account to another. */ function transfer(Token storage self, address sender, address to, uint256 value) internal { require(value <= self._balances[sender]); require(to != address(0)); self._balances[sender] = self._balances[sender].sub(value); self._balances[to] = self._balances[to].add(value); emit Transfer(sender, to, value); } /** * @dev Mint new tokens to an account. */ function mint(Token storage self, address account, uint256 value) internal { require(account != 0); self._totalSupply = self._totalSupply.add(value); self._balances[account] = self._balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Burn tokens from an account. */ function burn(Token storage self, address account, uint256 value) internal { require(account != 0); require(value <= self._balances[account]); self._totalSupply = self._totalSupply.sub(value); self._balances[account] = self._balances[account].sub(value); emit Transfer(account, address(0), value); } //////////////////////////////////////////////////////////////////////////// } contract HubCulture{ //////////////////////////////////////////////////////////////////////////// //Imports using ERC20Lib for ERC20Lib.Token; using SafeMath for uint256; /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// //Events event Pending(address indexed account, uint256 indexed value, uint256 indexed nonce); event Deposit(address indexed account, uint256 indexed value, uint256 indexed nonce); event Withdraw(address indexed account, uint256 indexed value, uint256 indexed nonce); event Decline(address indexed account, uint256 indexed value, uint256 indexed nonce); event Registration(address indexed account, bytes32 indexed uuid, uint256 indexed nonce); event Unregistered(address indexed account, uint256 indexed nonce); //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //Declarations mapping(address=>bool) authorities; mapping(address=>bool) registered; mapping(address=>bool) vaults; ERC20Lib.Token token; ERC20Lib.Token pending; uint256 eventNonce; address failsafe; address owner; bool paused; //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //Constructor constructor(address _owner,address _failsafe) public { failsafe = _failsafe; owner = _owner; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //Modifiers modifier onlyFailsafe(){ require(msg.sender == failsafe); _; } modifier onlyAdmin(){ require(msg.sender == owner || msg.sender == failsafe); _; } modifier onlyAuthority(){ require(authorities[msg.sender]); _; } modifier onlyVault(){ require(vaults[msg.sender]); _; } modifier notPaused(){ require(!paused); _; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //Failsafe Logic function isFailsafe(address _failsafe) public view returns (bool){ return (failsafe == _failsafe); } function setFailsafe(address _failsafe) public onlyFailsafe{ failsafe = _failsafe; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //Owner Logic function isOwner(address _owner) public view returns (bool){ return (owner == _owner); } function setOwner(address _owner) public onlyAdmin{ owner = _owner; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //Vault Logic function isVault(address vault) public view returns (bool) { return vaults[vault]; } function addVault(address vault) public onlyAdmin notPaused returns (bool) { vaults[vault] = true; return true; } function removeVault(address vault) public onlyAdmin returns (bool) { vaults[vault] = false; return true; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //Authority Logic function isAuthority(address authority) public view returns (bool) { return authorities[authority]; } function addAuthority(address authority) public onlyAdmin notPaused returns (bool) { authorities[authority] = true; return true; } function removeAuthority(address authority) public onlyAdmin returns (bool) { authorities[authority] = false; return true; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //Pause Logic /** * @dev Administrative lockdown check. **/ function isPaused() public view returns (bool) { return paused; } /** * @dev Locks down all actions except administrative actions. Should be used * to address security flaws. If this contract has a critical bug, This method * should be called to allow for a hault of operations and a migration to occur * If this method is called due to a loss of server keys, it will hault * operation until root cause may be found. **/ function pause() public onlyAdmin notPaused returns (bool) { paused = true; return true; } /** * @dev Releases system from administrative lockdown. Requires retrieval of * failsafe coldwallet. **/ function unpause() public onlyFailsafe returns (bool) { paused = false; return true; } /** * @dev Locks down all actions FOREVER! This should only be used in * manual contract migration due to critical bug. This will halt all *operations and allow a new contract to be built by transfering all balances. **/ function lockForever() public onlyFailsafe returns (bool) { pause(); setOwner(address(this)); setFailsafe(address(this)); return true; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //Panic Logic /** * @dev Lets everyone know if something catastrophic has occured. The owner, * and failsafe should not ever be the same entity. This combined with a paused * state indicates that panic has most likely been called or this contract has * been permanently locked for migration. */ function isBadDay() public view returns (bool) { return (isPaused() && (owner == failsafe)); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //ERC20Lib Wrappers /** * @dev These methods act as transparent wrappers around the ERC20Lib. The * only changes in logic are as follows: * - The msg.sender must be explicitly set by the wrapper * - The totalSupply has been broken up into 3 functions as totalSupply * pendingSupply, and activeSupply. * Pending supply is the supply that has been deposited but not released * Active supply is the released deposited supply * Total supply is the sum of active and pending. */ function totalSupply() public view returns (uint256) { uint256 supply = 0; supply = supply.add(pending.totalSupply()); supply = supply.add(token.totalSupply()); return supply; } function pendingSupply() public view returns (uint256) { return pending.totalSupply(); } function availableSupply() public view returns (uint256) { return token.totalSupply(); } function balanceOf(address account) public view returns (uint256) { return token.balances(account); } function allowance(address account, address spender) public view returns (uint256) { return token.allowance(account,spender); } function transfer(address to, uint256 value) public notPaused returns (bool) { token.transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public notPaused returns (bool) { token.approve(msg.sender,spender,value); return true; } function transferFrom(address from, address to, uint256 value) public notPaused returns (bool) { token.transferFrom(msg.sender,from,to,value); return true; } function increaseAllowance(address spender, uint256 addedValue) public notPaused returns (bool) { token.increaseAllowance(msg.sender,spender,addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public notPaused returns (bool) { token.decreaseAllowance(msg.sender,spender,subtractedValue); return true; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //Deposit Logic /** * @dev This logic allows for a delay between a deposit * and the release of funds. This is accomplished by maintaining * two independant ERC20 contracts in this one contract by using * the ERC20Lib library. * The first is the token contract that is used to transfer value * as is normally expected of an ERC20. The second is the system * that allows Ven to be dposited and withdrawn from the * blockchain such that no extra priveledge is given to HubCulture * for on blockchain actions. This system also allows for the time * delay based approval of deposits. Further, the entity that * creates a deposit request is an authority, but only a vault * may release the deposit into the active balances of the ERC20 * token. */ /** * @dev Deposit value from HubCulture into ERC20 * This is a pending deposit that must be released. * Only an authority may request a deposit. */ function deposit(address account, uint256 value) public notPaused onlyAuthority returns (bool) { pending.mint(account,value); eventNonce+=1; emit Pending(account,value,eventNonce); return true; } /** * @dev Release a deposit from pending state and credit * account with the balance due. */ function releaseDeposit(address account, uint256 value) public notPaused onlyVault returns (bool) { pending.burn(account,value); token.mint(account,value); eventNonce+=1; emit Deposit(account,value,eventNonce); return true; } /** * @dev Cancel a deposit. This prevents the deposit from * being released. */ function revokeDeposit(address account, uint256 value) public notPaused onlyVault returns (bool) { pending.burn(account,value); eventNonce+=1; emit Decline(account,value,eventNonce); return true; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //Withdraw Logic /** * @dev Withdraw tokens by burning the balance and emitting the event. * In order to withdraw the account must be a registered wallet. This is * to prevent loss of funds. */ function withdraw(uint256 value) public notPaused returns (bool) { require(registered[msg.sender]); token.burn(msg.sender,value); eventNonce+=1; emit Withdraw(msg.sender,value,eventNonce); return true; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //Wallet Registration Logic /** * @dev Allows the registration state of a wallet to be queried. */ function isRegistered(address wallet) public view returns (bool) { return registered[wallet]; } /** * @dev Allows a HubCulture user to claim thier wallet. This system works * as follows: * - User must enter the address they wish to claim on HubCulture * - The user will be provided with a UUID that will be a randomly * generated value (salt) hashed with the user ID for this user. * - The keccak256 of the uuid and account address will then be * signed by an authority to ensure authenticity. * - The user must submit a transaction, from the claimed account, with * the uuid, proof, and signature from the authority as arguments to * this method. * If all checks pass, the account registration event should be emitted, * and this account may now withdraw Ven to HubCulture. */ function register(bytes32 uuid, uint8 v, bytes32 r, bytes32 s) public notPaused returns (bool) { require(authorities[ecrecover(keccak256(abi.encodePacked(msg.sender,uuid)),v,r,s)]); registered[msg.sender]=true; eventNonce+=1; emit Registration(msg.sender, uuid, eventNonce); return true; } /** * @dev Allows an authority to unregister an account. This will prevent * a withdraw comand from being issued by this account unless it is * re-registered. This is not a security feature. This is a cleanup * function to ensure that closed accounts become zeroed out to minimize * chain bloat. */ function unregister(address wallet) public notPaused onlyAuthority returns (bool) { registered[wallet] = false; eventNonce+=1; emit Unregistered(wallet, eventNonce); return true; } //////////////////////////////////////////////////////////////////////////// }
* @dev Allows the registration state of a wallet to be queried./
function isRegistered(address wallet) public view returns (bool) { return registered[wallet]; }
1,756,318
[ 1, 19132, 326, 7914, 919, 434, 279, 9230, 358, 506, 23264, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 353, 10868, 12, 2867, 9230, 13, 203, 225, 1071, 203, 225, 1476, 203, 225, 1135, 261, 6430, 13, 288, 203, 565, 327, 4104, 63, 19177, 15533, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xDB36B3C61E155571b85431b0d2993ad3e23e9682/sources/SweepStakesToken.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a first supply mechanism has to be added in a derived contract using {_firstGenerate}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint256 private _fisrtSupply = 100000 * 10**18; uint256 private _divRate = 10000; uint256 public DevRate = 100; uint256 public RewardRate = 100; uint256 public BurningRate = 200; address public DevAddres; address public RewardPool; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, address _DevAddres, address _RewardPool) public { _name = name; _symbol = symbol; _decimals = 18; DevAddres = _DevAddres; RewardPool = _RewardPool; _firstGenerate(msg.sender, _fisrtSupply); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); uint256 devAmount = amount.mul(DevRate); uint256 farmingAmount = amount.mul(RewardRate); uint256 burningAmount = amount.mul(BurningRate); devAmount = devAmount.div(_divRate); farmingAmount = farmingAmount.div(_divRate); burningAmount = burningAmount.div(_divRate); _balances[recipient] = _balances[recipient].add((amount.sub(devAmount)).sub(farmingAmount)); emit Transfer(sender, recipient, ((amount.sub(devAmount)).sub(farmingAmount)).sub(burningAmount)); if(devAmount > 0 && DevAddres != address(0)){ _balances[DevAddres] = _balances[DevAddres].add(devAmount); emit Transfer(sender, DevAddres, devAmount); } if(farmingAmount > 0 && RewardPool != address(0)){ _balances[RewardPool] = _balances[RewardPool].add(farmingAmount); emit Transfer(sender, RewardPool, farmingAmount); } if(burningAmount > 0){ _totalSupply = _totalSupply.sub(burningAmount); emit Transfer(sender, address(0), burningAmount); } } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); uint256 devAmount = amount.mul(DevRate); uint256 farmingAmount = amount.mul(RewardRate); uint256 burningAmount = amount.mul(BurningRate); devAmount = devAmount.div(_divRate); farmingAmount = farmingAmount.div(_divRate); burningAmount = burningAmount.div(_divRate); _balances[recipient] = _balances[recipient].add((amount.sub(devAmount)).sub(farmingAmount)); emit Transfer(sender, recipient, ((amount.sub(devAmount)).sub(farmingAmount)).sub(burningAmount)); if(devAmount > 0 && DevAddres != address(0)){ _balances[DevAddres] = _balances[DevAddres].add(devAmount); emit Transfer(sender, DevAddres, devAmount); } if(farmingAmount > 0 && RewardPool != address(0)){ _balances[RewardPool] = _balances[RewardPool].add(farmingAmount); emit Transfer(sender, RewardPool, farmingAmount); } if(burningAmount > 0){ _totalSupply = _totalSupply.sub(burningAmount); emit Transfer(sender, address(0), burningAmount); } } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); uint256 devAmount = amount.mul(DevRate); uint256 farmingAmount = amount.mul(RewardRate); uint256 burningAmount = amount.mul(BurningRate); devAmount = devAmount.div(_divRate); farmingAmount = farmingAmount.div(_divRate); burningAmount = burningAmount.div(_divRate); _balances[recipient] = _balances[recipient].add((amount.sub(devAmount)).sub(farmingAmount)); emit Transfer(sender, recipient, ((amount.sub(devAmount)).sub(farmingAmount)).sub(burningAmount)); if(devAmount > 0 && DevAddres != address(0)){ _balances[DevAddres] = _balances[DevAddres].add(devAmount); emit Transfer(sender, DevAddres, devAmount); } if(farmingAmount > 0 && RewardPool != address(0)){ _balances[RewardPool] = _balances[RewardPool].add(farmingAmount); emit Transfer(sender, RewardPool, farmingAmount); } if(burningAmount > 0){ _totalSupply = _totalSupply.sub(burningAmount); emit Transfer(sender, address(0), burningAmount); } } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); uint256 devAmount = amount.mul(DevRate); uint256 farmingAmount = amount.mul(RewardRate); uint256 burningAmount = amount.mul(BurningRate); devAmount = devAmount.div(_divRate); farmingAmount = farmingAmount.div(_divRate); burningAmount = burningAmount.div(_divRate); _balances[recipient] = _balances[recipient].add((amount.sub(devAmount)).sub(farmingAmount)); emit Transfer(sender, recipient, ((amount.sub(devAmount)).sub(farmingAmount)).sub(burningAmount)); if(devAmount > 0 && DevAddres != address(0)){ _balances[DevAddres] = _balances[DevAddres].add(devAmount); emit Transfer(sender, DevAddres, devAmount); } if(farmingAmount > 0 && RewardPool != address(0)){ _balances[RewardPool] = _balances[RewardPool].add(farmingAmount); emit Transfer(sender, RewardPool, farmingAmount); } if(burningAmount > 0){ _totalSupply = _totalSupply.sub(burningAmount); emit Transfer(sender, address(0), burningAmount); } } function _firstGenerate(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: generate to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _setTransferRate(uint256 _DevRate, uint256 _RewardRate, uint256 _BurningRate) external onlyOwner { DevRate = _DevRate; RewardRate = _RewardRate; BurningRate = _BurningRate; } function setTransferAddress(address _DevAddres, address _RewardPool) external onlyOwner { DevAddres = _DevAddres; RewardPool = _RewardPool; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
15,646,136
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 1122, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 3645, 4625, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 9484, 2537, 635, 13895, 358, 7864, 350, 2641, 18, 4673, 16164, 434, 326, 512, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 202, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 565, 2254, 5034, 3238, 389, 74, 291, 3797, 3088, 1283, 273, 25259, 380, 1728, 636, 2643, 31, 203, 202, 203, 202, 11890, 5034, 3238, 389, 2892, 4727, 273, 12619, 31, 203, 202, 203, 202, 11890, 5034, 1071, 9562, 4727, 273, 2130, 31, 203, 202, 11890, 5034, 1071, 534, 359, 1060, 4727, 273, 2130, 31, 203, 202, 11890, 5034, 1071, 605, 321, 310, 4727, 273, 4044, 31, 203, 202, 203, 202, 2867, 1071, 9562, 986, 455, 31, 203, 202, 2867, 1071, 534, 359, 1060, 2864, 31, 203, 202, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 203, 203, 565, 3885, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 16, 1758, 389, 8870, 986, 455, 16, 1758, 389, 17631, 1060, 2864, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 3639, 389, 31734, 273, 6549, 31, 203, 1082, 203, 202, 202, 8870, 986, 455, 273, 389, 8870, 986, 455, 31, 203, 202, 202, 17631, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /*import "Register.sol"; import "Agora.sol"; import "Loi.sol"; import "API_Register.sol"; import "Delegation.sol"; import "IDelegation.sol"; import "Citizens_Register.sol"; import "IVote.sol"; */ import "contracts/Register.sol"; import "contracts/Agora.sol"; import "contracts/Loi.sol"; import "contracts/API_Register.sol"; import "contracts/Delegation.sol"; import "contracts/Citizens_Register.sol"; import "contracts/IVote.sol"; /** * @notice {Constitution_Register} library is used to reduce the size of Constitution contract in order to avoid to exceed contract limit size. It contains heavy functions and data structures. */ library Constitution_Register{ /** * @dev Deploy a {Loi} contract and returns it's address. * @param Loi_Name Name of the Loi contract * @param agora Addres of the Project's {Agora} contract */ function Create_Loi(string memory Loi_Name, address agora)external returns(address){ Loi loi = new Loi(Loi_Name, agora); //loi.Add_Authority(authority); return address(loi); } /** * @dev Deploy a {API_Register} contract and returns it's address. * @param Name Name of the API_Register contract * @param agora Addres of the Project's {Agora} contract */ function Create_API(string memory Name, address agora) external returns(address){ return address(new API_Register(Name, agora)); } } /** * @notice {Constitution_Delegation} library is used to reduce the size of Constitution contract in order to avoid to exceed contract limit size. It contains heavy functions and data structures. */ library Constitution_Delegation{ /** * @dev Deploy a {Delegation} contract and returns it's address. * @param Delegation_Name Name of the Delegation contract * @param Initial_members List of initial memebers of the delegation * @param Token_Address Address of the Project's {DemoCoin} contract * @param citizen_address Addres of the Project's {Citizens_Register} contract * @param agora_address Addres of the Project's {Agora} contract */ function Create_Delegation(string memory Delegation_Name, address[] calldata Initial_members, address Token_Address, address citizen_address, address agora_address)external returns(address){ Delegation delegation = new Delegation(Delegation_Name, Initial_members, Token_Address, citizen_address, agora_address); return address(delegation); } } /** * @notice Constitution register contract is used to edit parameters of a Web3 Direct Democracy project. * It contains address of all deployed contracts used in a project. Particularly, it contains a list of address of all register contracts that are used in the project, and another list for all Delegations. * Hence, Constitution is the central contract in a project. To launch a Web3 Direct Democracy project, we have to launch the Constitution contract. * From Constitution deployed contract, we can have access to all the project. There is a single Constitution contract in a project. * With Constitution register contract, we can add new register and delegations to the project, we can modify their democratic process parameters, change other register’s _Register_Authorities_ array… * Constitution contract goal is to customize the project to specific use cases and to keep it updatable. * * Once a Web3 Direct Democracy project has just been deployed, it hasn’t any register or delegation. Citizens_Register and DemoCoin contracts haven’t any authority in their _Register_Authorities_ list. * Thus, at the beginning of a Web3 Direct Democracy project, we need an initialisation stage. * In this initialisation stage, there is a _Transitional_Government_ account that has authority on the constitution and can quickly perform necessary operations without passing by any democratic process : */ contract Constitution is Register{ using EnumerableSet for EnumerableSet.AddressSet; // event Register_Parameters_Modified(address); event Register_Created(address register); event Delegation_Created(address delegation); event Transitional_Government_Finised(); Agora public Agora_Instance; Citizens_Register public Citizen_Instance; DemoCoin public Democoin_Instance; //IVote public majority_judgment_ballot; //address public Citizens_Address; address public Transitional_Government; //mapping(address=>Constitution_Register.Register_Parameters) Registers; EnumerableSet.AddressSet Registers_Address_List; //mapping(address=>Constitution_Delegation.Delegation_Parameters) Delegations; EnumerableSet.AddressSet Delegation_Address_List; /** * @param Constitution_Name Name of the Constitution contract * @param DemoCoin_Address Address of the {DemoCoin} contract of the project * @param Citizen_Address Address of the {Citizens_Register} contract of the project * @param Agora_Address Address of the {Agora} contract of the project * @param transition_government Address of the Transitional_Government. */ constructor(string memory Constitution_Name, address DemoCoin_Address, address Citizen_Address, address Agora_Address, address transition_government) Register(Constitution_Name){ require(transition_government !=address(0)); Constitution_Address = address(this); //Type_Institution = Institution_Type.CONSTITUTION; /*Democoin = new DemoCoin(Token_Name, Token_Symbole, initial_citizens, initial_citizens_token_amount); Citizen_Instance = new Citizens_Register(Citizen_Name, initial_citizens, address(Democoin), new_citizen_mint_amount); Agora_Instance = new Agora(Agora_Name, address(Democoin), address(Citizen_Instance));*/ Democoin_Instance = DemoCoin(DemoCoin_Address); Citizen_Instance = Citizens_Register(Citizen_Address); Agora_Instance = Agora(Agora_Address); //majority_judgment_ballot = new majority_judgment_ballot(); //Citizens_Address = Constitution_Register.Create_Citizens(initial_citizens); Transitional_Government = transition_government; Register_Authorities.add(Transitional_Government); Register_Authorities.add(Agora_Address); } /** * @dev Function called by the {Transitional_Government} account to end the Transitional Government stage. This step is mandatory to start using a Web3 Direct Democracy in a safe way. */ function End_Transition_Government()external{ require(msg.sender == Transitional_Government, "Transitional_Government only"); Register_Authorities.remove(Transitional_Government); emit Transitional_Government_Finised(); } /** * @dev Add a new address to a Register contract's (contract that inherit from a {Register} abstract contract) {Register_Authorities} list. * @param register Address of the register contract * @param authority Address to add to the {Register_Authorities} list. */ function Add_Register_Authority(address register, address authority) external Register_Authorities_Only{ require(Registers_Address_List.contains(register), "Unknown Register"); Register res = Register(register); res.Add_Authority(authority); } /** * @dev Removes a, address from a Register contract's {Register_Authorities} list. * @param register Address of the register contract * @param authority Address to remove from the {Register_Authorities} list. */ function Remove_Register_Authority(address register, address authority) external Register_Authorities_Only{ require(Registers_Address_List.contains(register), "Unknown Register"); Register res = Register(register); res.Remove_Authority(authority); } /** * @dev Change the Constitution address of an Institution contract belonging to current project. After this call, this Institution will not recognize this Constitution anymore. * @param institution_address Address of the Institution contract * @param new_address New Constitution address of the {institution_address} Institution */ function Set_Instances_Constitution(address institution_address, address new_address)external Register_Authorities_Only{ require(Registers_Address_List.contains(institution_address) || Delegation_Address_List.contains(institution_address) || institution_address== address(Citizen_Instance), "instance address unknown"); // There is no interest to modify Agora's constitution. require(new_address!=address(0),"address 0"); Institution Insti = Institution(institution_address); Institution_Type type_insti = Insti.Type_Institution(); require(type_insti != Institution_Type.CONSTITUTION); Insti.Set_Constitution(new_address); } /** * @dev Change the Name of an Institution contract. * @param institution_address Address of the Institution contract * @param name New name of the {institution_address} Institution. */ function Set_Institution_Name(address institution_address, string calldata name)external Register_Authorities_Only{ require(Registers_Address_List.contains(institution_address) || Delegation_Address_List.contains(institution_address) || institution_address== address(Citizen_Instance) || institution_address== address(Agora_Instance), "instance address unknown"); Institution Insti = Institution(institution_address); Insti.Set_Name(name); } /*FUNCTIONCALL API functions*/ /*DemoCoin functions*/ /** * @dev Change address that are allowed to mint DemoCoin Token (Minter authorities). They are contained in the {Mint_Authorities} list of {DemoCoin} contract. * @param Add_Minter List of new Minter address * @param Remove_Minter List of Minter address to remove from {Mint_Authorities} */ function Set_Minnter(address[] calldata Add_Minter, address[] calldata Remove_Minter)external Register_Authorities_Only{ uint add_len=Add_Minter.length; uint remove_len = Remove_Minter.length; for(uint i =0; i<add_len;i++){ Democoin_Instance.Add_Minter(Add_Minter[i]); } for(uint j=0; j<remove_len; j++){ Democoin_Instance.Remove_Minter(Remove_Minter[j]); } } /** * @dev Change address that are allowed to burn DemoCoin Token (Burner authorities). They are contained in the {Burn_Authorities} list of {DemoCoin} contract. * @param Add_Burner List of new Burner address * @param Remove_Burner List of Burner address to remove from {Burn_Authorities} */ function Set_Burner(address[] calldata Add_Burner, address[] calldata Remove_Burner)external Register_Authorities_Only{ uint add_len=Add_Burner.length; uint remove_len = Remove_Burner.length; for(uint i =0; i<add_len;i++){ Democoin_Instance.Add_Burner(Add_Burner[i]); } for(uint j=0; j<remove_len; j++){ Democoin_Instance.Remove_Burner(Remove_Burner[j]); } } /*Citizens_Register Handling*/ /** * @dev Change the amount of DemoCoin token to mint for new registered citizens. * @param amount Amount of token to mint. */ function Set_Citizen_Mint_Amount(uint amount) external Register_Authorities_Only{ Citizen_Instance.Set_Citizen_Mint_Amount(amount); } /** * @dev Removes address from {Citizens_Registering_Authorities} (address allowed to register new citizens) and/or from {Citizens_Banning_Authorities} (address allowed to ban citizens) * @param removed_authority Address to removes {Citizens_Register} contract authorities lists. */ function Citizen_Register_Remove_Authority(address removed_authority) external Register_Authorities_Only{ Citizen_Instance.Remove_Authority(removed_authority); } /** * @dev Allows an address to register new citizens. The address is added to {Citizens_Registering_Authorities} list * @param new_authority Address to add to {Citizens_Registering_Authorities} list */ function Add_Registering_Authority(address new_authority)external Register_Authorities_Only{ Citizen_Instance.Add_Registering_Authority(new_authority); } /** * @dev Allows an address to register ban citizens. The address is added to {Citizens_Banning_Authorities} list * @param new_authority Address to add to {Citizens_Banning_Authorities} list */ function Add_Banning_Authority(address new_authority)external Register_Authorities_Only{ Citizen_Instance.Add_Banning_Authority(new_authority); } /*Register/Agora Handling*/ /** * @dev Add/create a new Register Contract to the Web3 Direct Democracy project. It's address is added to {Registers_Address_List} * @param Name Name of the new Register contract * @param register_type Type of the Register Contract (see {Institution_Type} enum of {Institution} abstract contract). * @param Petition_Duration Duration of the proposition/petition stage * @param Vote_Duration Duration of the voting stage * @param Vote_Checking_Duration Duration of the validation stage * @param Law_Initialisation_Price Amount of DemoCoin token to pay to submit a new Referendum proposition. * @param FunctionCall_Price Amount of DemoCoin token to pay for each new function call of a function call corpus proposal submission. * @param Required_Petition_Rate The minimum ratio of citizens signatures required to submit the referendum proposition as a referendum to all citizens. * @param Ivote_address Address of the IVote contract used in the voting and validation stage */ function Create_Register(string memory Name, uint8 register_type, uint Petition_Duration, uint Vote_Duration, uint Vote_Checking_Duration, uint Law_Initialisation_Price, uint FunctionCall_Price, uint16 Required_Petition_Rate, address Ivote_address) external Register_Authorities_Only{ //returns(bool, bytes memory){ address new_register_address; if(register_type == 0){ new_register_address = address(this); }else if(register_type == 3){ new_register_address = Constitution_Register.Create_Loi(Name, address(Agora_Instance)); }else if(register_type == 4){ new_register_address = Constitution_Register.Create_API(Name, address(Agora_Instance)); }else{ revert("Not Register Type"); } require(!Registers_Address_List.contains(new_register_address), "Register Already Existing"); Registers_Address_List.add(new_register_address); Agora_Instance.Create_Register_Referendum(new_register_address, register_type); _Set_Register_Param(new_register_address, Petition_Duration, Vote_Duration, Vote_Checking_Duration, Law_Initialisation_Price, FunctionCall_Price, Required_Petition_Rate, Ivote_address); emit Register_Created(new_register_address); } /** * @dev Change parameters of a Register Contract of the project. * @param register_address Address of the Register contract * @param Petition_Duration Duration of the proposition/petition stage * @param Vote_Duration Duration of the voting stage * @param Vote_Checking_Duration Duration of the validation stage * @param Law_Initialisation_Price Amount of DemoCoin token to pay to submit a new Referendum proposition. * @param FunctionCall_Price Amount of DemoCoin token to pay for each new function call of a function call corpus proposal submission. * @param Required_Petition_Rate The minimum ratio of citizens signatures required to submit the referendum proposition as a referendum to all citizens. * @param Ivote_address Address of the IVote contract used in the voting and validation stage */ function Set_Register_Param(address register_address, uint Petition_Duration, uint Vote_Duration, uint Vote_Checking_Duration, uint Law_Initialisation_Price, uint FunctionCall_Price, uint16 Required_Petition_Rate, address Ivote_address) external Register_Authorities_Only{ //returns(bool, bytes memory){ require(Registers_Address_List.contains(register_address), "Register doesn't exist"); _Set_Register_Param(register_address, Petition_Duration, Vote_Duration, Vote_Checking_Duration, Law_Initialisation_Price, FunctionCall_Price, Required_Petition_Rate, Ivote_address); } function _Set_Register_Param(address register_address, uint Petition_Duration, uint Vote_Duration, uint Vote_Checking_Duration, uint Law_Initialisation_Price, uint FunctionCall_Price, uint16 Required_Petition_Rate, address Ivote_address) internal { if(Petition_Duration ==0 || Vote_Duration ==0 || Required_Petition_Rate == 0 || Required_Petition_Rate >10000 || Ivote_address==address(0)){ revert("Bad arguments value"); } Agora_Instance.Update_Register_Referendum_Parameters(register_address, Petition_Duration, Vote_Duration, Vote_Checking_Duration, Law_Initialisation_Price, FunctionCall_Price, Required_Petition_Rate, Ivote_address); } /*Delegations Handling*/ /** * @dev Add/Deploy a new Delegation contract to the project. It's address is added to {Delegation_Address_List} * @param Name Name of the Delegation contract * @param delegation_address Address of an already deployed Delegation contract to add to the Project. If the delegation_address argument is address(0) then the function deploy a new Delegation contract. * @param Uint256_Legislatifs_Arg Array of uitn256 parameters related to Delegation's legislatif process. We use an array in order to reduce stack size (to avoid the "stack too deep" error). Array elements represent following parameters: * - Member_Max_Token_Usage: The maximum amount of token a member is allowed to use for a law project elaboration * - Law_Initialisation_Price: The price in token for creating a law project * - FunctionCall_Price: The price in token for one FunctionCall. * - Proposition_Duration: The duration of the stage in which members are allowed to submit propositions * - Vote_Duration: The duration of the stage in which members are allowed to vote for the proposition they want * - Law_Censor_Period_Duration: The duration of the stage in which all citizens are allowed to sign a etition against the law project proposed by the Delegation * * @param Uint256_Governance_Arg Array of uitn256 parameters related to Delegation's Internal governance. We use an array in order to reduce stack size (to avoid the "stack too deep" error). Array elements represent following parameters: * - Election_Duration: Duration of the stage in which citizens are allowed to vote for Candidats they prefer * - Validation_Duration: Duration of the stage in which citizens can validate their hased vote by revealing their choice and the salt that has been used for hasing * - Mandate_Duration: Duration of a delegation mandate * - Immunity_Duration: Amount of time after the beginning of a new mandate during which delegation's members can't be revoked * - Mint_Token: Amount of token to mint for the Delegation * @param Num_Max_Members Maximum number of members in the delegation. * @param Revert_Proposition_Petition_Rate The minimum ratio of citizens required to cancel a law project * @param Revert_Penalty_Rate Ratio of total amount of token belonged by the delegation that will be lost if a law project is rejected by citizens * @param New_Election_Petition_Rate The minimum ratio of citizens required to revoke the current delegation's members and start a new election * @param Initial_members: Initials members of the delegation * @param Ivote_address_legislatif Address of the IVote contract that will be used during Legislatif process * @param Ivote_address_governance Address of the IVote contract that will be used during election stage */ function Create_Delegation(string memory Name, address delegation_address, uint[6] calldata Uint256_Legislatifs_Arg, uint[5] calldata Uint256_Governance_Arg, uint16 Num_Max_Members, uint16 Revert_Proposition_Petition_Rate, uint16 Revert_Penalty_Rate, uint16 New_Election_Petition_Rate, address[] memory Initial_members, address Ivote_address_legislatif, address Ivote_address_governance) external Register_Authorities_Only { if(Uint256_Legislatifs_Arg[3]==0 || Uint256_Legislatifs_Arg[4]==0 || Revert_Proposition_Petition_Rate>10000 || Revert_Penalty_Rate>10000 || Ivote_address_legislatif==address(0)){ revert("Legislatif: Bad Argument Value"); } if(Uint256_Governance_Arg[0]==0 || Uint256_Governance_Arg[2]==0 || Num_Max_Members==0 || New_Election_Petition_Rate ==0 || New_Election_Petition_Rate>10000 || Initial_members.length > Num_Max_Members || Ivote_address_governance==address(0)){ revert("Governance: Bad Argument Value"); } if(delegation_address == address(0)){ //Create a new delegation for(uint i =0; i<Initial_members.length; i++){ require(Citizen_Instance.Contains(Initial_members[i]), "Member is not citizen"); } delegation_address = Constitution_Delegation.Create_Delegation(Name, Initial_members, address(Democoin_Instance), address(Citizen_Instance), address(Agora_Instance)); }else{ require(!Delegation_Address_List.contains(delegation_address), "Delegation already registered"); } Delegation_Address_List.add(delegation_address); emit Delegation_Created(delegation_address); if(Uint256_Governance_Arg[4]>0){ Democoin_Instance.Mint(delegation_address, Uint256_Governance_Arg[4]); } IDelegation(delegation_address).Update_Legislatif_Process(Uint256_Legislatifs_Arg, Revert_Proposition_Petition_Rate, Revert_Penalty_Rate, Ivote_address_legislatif); IDelegation(delegation_address).Update_Internal_Governance(Uint256_Governance_Arg[0], Uint256_Governance_Arg[1], Uint256_Governance_Arg[2], Uint256_Governance_Arg[3], Num_Max_Members, New_Election_Petition_Rate, Ivote_address_governance); } /** * @dev Put a Register contract under the control of a Delegation. The Register contract address is added to {Controled_Registers} list of the Delegation. * It means that the Delegation recognize the Register contract as a controled one. But to allow the Delegation to call Register functions of the Register contract, you also have to to add the Delegation' address to the {Register_Authorities} list of the register contract via the {Add_Register_Authority} function. * @param delegation_address Address of the Delegation * @param new_controled_register Address of the Register contract. */ function Add_Delegation_Controled_Register(address delegation_address, address new_controled_register) external Register_Authorities_Only{ require(Delegation_Address_List.contains(delegation_address), "Non Existing Delegation"); require(Registers_Address_List.contains(new_controled_register), "Non Existing Register"); IDelegation(delegation_address).Add_Controled_Register( new_controled_register); } /** * @dev Removes a Register contract from the control of a Delegation. The Register contract address is removed from the {Controled_Registers} list of the Delegation. * It means that the Delegation doesn't recognize anymore the Register contract as a controled one. But to fully cut bonds between the Delegation and the Register contract, you also have to to remove the Delegation' address from the {Register_Authorities} list of the register contract via the {Remove_Register_Authority} function. * @param delegation_address Address of the Delegation * @param removed_controled_register Address of the Register contract. */ function Remove_Delegation_Controled_Register(address delegation_address, address removed_controled_register) external Register_Authorities_Only{ require(Delegation_Address_List.contains(delegation_address), "Non Existing Delegation"); require(Registers_Address_List.contains(removed_controled_register), "Non Existing Register"); IDelegation(delegation_address).Remove_Controled_Register( removed_controled_register); } /** * @dev Modify parameters related to the Legislatif process of a Delegation. * @param delegation_address Address of the Delegation contract * @param delegation_address Address of an already deployed Delegation contract to add to the Project. If the delegation_address argument is address(0) then the function deploy a new Delegation contract. * @param Uint256_Legislatifs_Arg Array of uitn256 parameters related to Delegation's legislatif process. We use an array in order to reduce stack size (to avoid the "stack too deep" error). Array elements represent following parameters: * - Member_Max_Token_Usage: The maximum amount of token a member is allowed to use for a law project elaboration * - Law_Initialisation_Price: The price in token for creating a law project * - FunctionCall_Price: The price in token for one FunctionCall. * - Proposition_Duration: The duration of the stage in which members are allowed to submit propositions * - Vote_Duration: The duration of the stage in which members are allowed to vote for the proposition they want * - Law_Censor_Period_Duration: The duration of the stage in which all citizens are allowed to sign a etition against the law project proposed by the Delegation * * @param Revert_Proposition_Petition_Rate The minimum ratio of citizens required to cancel a law project * @param Revert_Penalty_Rate Ratio of total amount of token belonged by the delegation that will be lost if a law project is rejected by citizens * @param Ivote_address Address of the IVote contract that will be used during Legislatif process */ function Set_Delegation_Legislatif_Process(address delegation_address, uint[6] calldata Uint256_Legislatifs_Arg, uint16 Revert_Proposition_Petition_Rate, uint16 Revert_Penalty_Rate, address Ivote_address) external Register_Authorities_Only{ //returns(bool, bytes memory){ require(Delegation_Address_List.contains(delegation_address), "Non Existing Delegation"); if(Uint256_Legislatifs_Arg[3]==0 || Uint256_Legislatifs_Arg[4]==0 || Revert_Proposition_Petition_Rate>10000 || Revert_Penalty_Rate>10000 || Ivote_address==address(0) ){ revert("Legislatif: Bad Argument Value"); } IDelegation(delegation_address).Update_Legislatif_Process(Uint256_Legislatifs_Arg, Revert_Proposition_Petition_Rate, Revert_Penalty_Rate, Ivote_address); } /** * @dev Modify parameters related to the Legislatif process of a Delegation. * @param delegation_address Address of the Delegation contract * @param Election_Duration: Duration of the stage in which citizens are allowed to vote for Candidats they prefer * @param Validation_Duration: Duration of the stage in which citizens can validate their hased vote by revealing their choice and the salt that has been used for hasing * @param Mandate_Duration: Duration of a delegation mandate * @param Immunity_Duration: Amount of time after the beginning of a new mandate during which delegation's members can't be revoked * @param Num_Max_Members: Maximum number of members in the delegation. * @param New_Election_Petition_Rate: The minimum ratio of citizens required to revoke the current delegation's members and start a new election * @param Mint_Token Amount of token to mint for the Delegation: Initials members of the delegation * @param Ivote_address Address of the IVote contract that will be used during election stage */ function Set_Delegation_Internal_Governance(address delegation_address, uint Election_Duration, uint Validation_Duration, uint Mandate_Duration, uint Immunity_Duration, uint16 Num_Max_Members, uint16 New_Election_Petition_Rate, uint Mint_Token, address Ivote_address) external Register_Authorities_Only{ require(Delegation_Address_List.contains(delegation_address), "Non Existing Delegation"); if(Election_Duration==0 || Mandate_Duration==0 || Num_Max_Members==0 || New_Election_Petition_Rate ==0 || New_Election_Petition_Rate>10000 || Ivote_address==address(0)){ revert("Governance: Bad Argument Value"); } if(Mint_Token>0){ Democoin_Instance.Mint(delegation_address, Mint_Token); } IDelegation(delegation_address).Update_Internal_Governance(Election_Duration, Validation_Duration, Mandate_Duration, Immunity_Duration, Num_Max_Members, New_Election_Petition_Rate, Ivote_address); } /*GETTERS*/ /** * @dev Get the list of all address of Register contracts registered in the Constitution * @return register_list Array of Register contract address */ function Get_Register_List() external view returns(bytes32[] memory register_list){ return Registers_Address_List._inner._values; } /** * @dev Get the list of all address of Delegation contracts registered in the Constitution * @return delegation_list Array of Delegation contract address */ function Get_Delegation_List() external view returns(bytes32[] memory delegation_list){ return Delegation_Address_List._inner._values; } }
GETTERS*/* @dev Get the list of all address of Register contracts registered in the Constitution @return register_list Array of Register contract address/
function Get_Register_List() external view returns(bytes32[] memory register_list){ return Registers_Address_List._inner._values; }
12,741,948
[ 1, 7113, 1470, 11367, 19, 225, 968, 326, 666, 434, 777, 1758, 434, 5433, 20092, 4104, 316, 326, 735, 14278, 327, 1744, 67, 1098, 1510, 434, 5433, 6835, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 445, 968, 67, 3996, 67, 682, 1435, 3903, 1476, 1135, 12, 3890, 1578, 8526, 3778, 1744, 67, 1098, 15329, 203, 540, 327, 2526, 6045, 67, 1887, 67, 682, 6315, 7872, 6315, 2372, 31, 203, 377, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x29f8aBB4cAB4BbB56F617D9a3c0F62D33758E74e/sources/contracts/PositionManagerWrappedCollateralToken.f.sol
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't need to send a transaction, and thus is not required to hold Ether at all./ solhint-disable-next-line func-name-mixedcase
interface IERC20Permit { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function nonces(address owner) external view returns (uint256); function DOMAIN_SEPARATOR() external view returns (bytes32); pragma solidity 0.8.19; }
9,690,701
[ 1, 1358, 434, 326, 4232, 39, 3462, 13813, 305, 2710, 15632, 6617, 4524, 358, 506, 7165, 3970, 14862, 16, 487, 2553, 316, 15605, 326, 288, 457, 1938, 97, 707, 16, 1492, 848, 506, 1399, 358, 2549, 392, 2236, 1807, 4232, 39, 3462, 1699, 1359, 261, 5946, 288, 45, 654, 39, 3462, 17, 5965, 1359, 6792, 635, 3430, 310, 279, 883, 6726, 635, 326, 2236, 18, 2525, 486, 283, 6291, 603, 288, 45, 654, 39, 3462, 17, 12908, 537, 5779, 326, 1147, 10438, 2236, 3302, 1404, 1608, 358, 1366, 279, 2492, 16, 471, 12493, 353, 486, 1931, 358, 6887, 512, 1136, 622, 777, 18, 19, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1326, 17, 529, 17, 19562, 3593, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 3462, 9123, 305, 288, 203, 565, 445, 21447, 12, 203, 3639, 1758, 3410, 16, 203, 3639, 1758, 17571, 264, 16, 203, 3639, 2254, 5034, 460, 16, 203, 3639, 2254, 5034, 14096, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 1731, 1578, 436, 16, 203, 3639, 1731, 1578, 272, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 1661, 764, 12, 2867, 3410, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 27025, 67, 4550, 1435, 3903, 1476, 1135, 261, 3890, 1578, 1769, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 3657, 31, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// // Подробнее о правилах: http://www.solarix.ru/for_developers/docs/rules.shtml // CD->26.03.2009 // LC->26.03.2009 #include "aa_rules.inc" #pragma floating off automat aa { /* operator FastAdjNoun_1 : RusSA_Instant_AdjNoun { // Для пушистой кошки // Вижу пушистую кошку // Пушистая кошка спит // Видеть пушистую кошку // Увидев пушистую кошку // Я пушистую кошку не вижу // Кто пушистую кошку видит if context { * Прилагательное:*{ ~СТЕПЕНЬ:СРАВН } Существительное:*{} } correlate { 1:РОД=2:РОД 1:ЧИСЛО=2:ЧИСЛО 1:ПАДЕЖ=2:ПАДЕЖ } then { if or( context { Предлог * * }, context { Существительное * * }, context { _НАЧ * * }, context { Глагол * * }, context { Инфинитив * * }, context { Деепричастие * * }, context { Местоимение * * }, context { Местоим_Сущ * * }, context { ЕСЛИ * * } ) then { context { 0 2.<ATTRIBUTE>1 } } } } */ operator FastAdjNoun_1 : RusSA_Instant_AdjNoun { // Для пушистой кошки // Вижу пушистую кошку // Пушистая кошка спит // Видеть пушистую кошку // Увидев пушистую кошку // Я пушистую кошку не вижу // Кто пушистую кошку видит if context { _НАЧ Прилагательное:*{ ~СТЕПЕНЬ:СРАВН } Существительное:*{} } correlate { 1:РОД=2:РОД 1:ЧИСЛО=2:ЧИСЛО 1:ПАДЕЖ=2:ПАДЕЖ } then { context { 0 2.<ATTRIBUTE>1 } } } operator FastAdjNoun_2 : RusSA_Instant_AdjNoun { if context { * * Прилагательное:*{ ~СТЕПЕНЬ:СРАВН } Существительное:*{} } correlate { 2:РОД=3:РОД 2:ЧИСЛО=3:ЧИСЛО 2:ПАДЕЖ=3:ПАДЕЖ } then { if and( or( context { Существительное * * * }, context { Глагол * * * }, context { Инфинитив * * * }, context { Деепричастие * * * }, context { Наречие * * * }, context { Местоимение * * * }, context { Местоим_Сущ * * * }, context { _НАЧ * * * } ), or( context { * Пунктуатор * * }, context { * Союз * * } ) ) then { context { 0 1 3.<ATTRIBUTE>2 } } } } operator FastAdjNoun_3 : RusSA_Instant_AdjNoun { // Для большой пушистой кошки // Вижу большую пушистую кошку // Большая пушистая кошка спит // Видеть большую пушистую кошку // Увидев большую пушистую кошку // Я большую пушистую кошку не вижу // Кто большую пушистую кошку видит if context { * Прилагательное:*{ ~СТЕПЕНЬ:СРАВН } Прилагательное:*{ ~СТЕПЕНЬ:СРАВН } Существительное:*{} } correlate { 1:РОД=3:РОД 1:ЧИСЛО=3:ЧИСЛО 1:ПАДЕЖ=3:ПАДЕЖ 2:РОД=3:РОД 2:ЧИСЛО=3:ЧИСЛО 2:ПАДЕЖ=3:ПАДЕЖ } then { if or( context { Предлог * * * }, context { Существительное * * * }, context { _НАЧ * * * }, context { Глагол * * * }, context { Инфинитив * * * }, context { Деепричастие * * * }, context { Местоимение * * * }, context { Местоим_Сущ * * * }, context { ЕСЛИ * * * } ) then { context { 0 3.{ <ATTRIBUTE>1 <ATTRIBUTE>2 } } } } } operator FastAdjNoun_4 : RusSA_Instant_AdjNoun { // Для нашей большой пушистой кошки // Вижу нашу большую пушистую кошку // Наша большая пушистая кошка спит // Видеть нашу большую пушистую кошку // Увидев нашу большую пушистую кошку // Я нашу большую пушистую кошку не вижу // Кто нашу большую пушистую кошку видит if context { * Прилагательное:*{ ~СТЕПЕНЬ:СРАВН } Прилагательное:*{ ~СТЕПЕНЬ:СРАВН } Прилагательное:*{ ~СТЕПЕНЬ:СРАВН } Существительное:*{} } correlate { 1:РОД=4:РОД 1:ЧИСЛО=4:ЧИСЛО 1:ПАДЕЖ=4:ПАДЕЖ 2:РОД=4:РОД 2:ЧИСЛО=4:ЧИСЛО 2:ПАДЕЖ=4:ПАДЕЖ 3:РОД=4:РОД 3:ЧИСЛО=4:ЧИСЛО 3:ПАДЕЖ=4:ПАДЕЖ } then { if or( context { Предлог * * * * }, context { Существительное * * * * }, context { _НАЧ * * * * }, context { Глагол * * * * }, context { Инфинитив * * * * }, context { Деепричастие * * * * }, context { Местоимение * * * * }, context { Местоим_Сущ * * * * }, context { ЕСЛИ * * * * } ) then { context { 0 4.{ <ATTRIBUTE>1 <ATTRIBUTE>2 <ATTRIBUTE>3 } } } } } } #pragma floating on
Для пушистой кошки Вижу пушистую кошку Пушистая кошка спит Видеть пушистую кошку Увидев пушистую кошку Я пушистую кошку не вижу Кто пушистую кошку видит
{ then { if or( ) then { } } } operator FastAdjNoun_1 : RusSA_Instant_AdjNoun
12,644,257
[ 1, 145, 247, 145, 124, 146, 242, 225, 145, 128, 146, 230, 146, 235, 145, 121, 146, 228, 146, 229, 145, 127, 145, 122, 225, 145, 123, 145, 127, 146, 235, 145, 123, 145, 121, 225, 145, 245, 145, 121, 145, 119, 146, 230, 225, 145, 128, 146, 230, 146, 235, 145, 121, 146, 228, 146, 229, 146, 230, 146, 241, 225, 145, 123, 145, 127, 146, 235, 145, 123, 146, 230, 225, 145, 258, 146, 230, 146, 235, 145, 121, 146, 228, 146, 229, 145, 113, 146, 242, 225, 145, 123, 145, 127, 146, 235, 145, 123, 145, 113, 225, 146, 228, 145, 128, 145, 121, 146, 229, 225, 145, 245, 145, 121, 145, 117, 145, 118, 146, 229, 146, 239, 225, 145, 128, 146, 230, 146, 235, 145, 121, 146, 228, 146, 229, 146, 230, 146, 241, 225, 145, 123, 145, 127, 146, 235, 145, 123, 146, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 288, 7010, 282, 1508, 203, 565, 288, 203, 377, 309, 578, 12, 203, 1850, 262, 203, 1377, 1508, 203, 4202, 288, 203, 4202, 289, 3639, 203, 565, 289, 377, 203, 289, 7010, 7010, 3726, 9545, 17886, 50, 465, 67, 21, 294, 534, 407, 5233, 67, 10675, 67, 17886, 50, 465, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.7.0; contract AdoreFinanceToken { // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } /*============================== = EVENTS = ==============================*/ event Reward( address indexed to, uint256 rewardAmount, uint256 level ); event RewardWithdraw( address indexed from, uint256 rewardAmount ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "Adore Finance Token"; string public symbol = "XFA"; uint8 constant public decimals = 0; uint256 public totalSupply_ = 2000000; uint256 constant internal tokenPriceInitial_ = 0.00012 ether; uint256 constant internal tokenPriceIncremental_ = 25000000; uint256 public currentPrice_ = tokenPriceInitial_ + tokenPriceIncremental_; uint256 public base = 1; uint256 public basePrice = 400; uint public percent = 500; uint public referralPercent = 1000; uint public sellPercent = 1500; mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal rewardBalanceLedger_; address commissionHolder; uint256 internal tokenSupply_ = 0; mapping(address => bool) internal administrators; mapping(address => address) public genTree; mapping(address => uint256) public level1Holding_; address payable internal creator; address payable internal management; //for management funds address internal poolFund; uint8[] percent_ = [7,2,1]; uint8[] adminPercent_ = [37,37,16,10]; address dev1; address dev2; address dev3; address dev4; constructor() { creator = msg.sender; administrators[creator] = true; } function isContract(address account) public 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); } function withdrawRewards(address payable _customerAddress, uint256 _amount) onlyAdministrator() public returns(uint256) { require(rewardBalanceLedger_[_customerAddress]>_amount && _amount > 3000000000000000); rewardBalanceLedger_[commissionHolder] += 3000000000000000; rewardBalanceLedger_[_customerAddress] -= _amount; emit RewardWithdraw(_customerAddress,_amount); _amount = SafeMath.sub(_amount, 3000000000000000); _customerAddress.transfer(_amount); } function setDevs(address _dev1, address _dev2, address _dev3, address _dev4) onlyAdministrator() public{ dev1 = _dev1; dev2 = _dev2; dev3 = _dev3; dev4 = _dev4; } function distributeCommission() onlyAdministrator() public returns(bool) { require(rewardBalanceLedger_[management]>100000000000000); rewardBalanceLedger_[dev1] += (rewardBalanceLedger_[management]*3700)/10000; rewardBalanceLedger_[dev2] += (rewardBalanceLedger_[management]*3700)/10000; rewardBalanceLedger_[dev3] += (rewardBalanceLedger_[management]*1600)/10000; rewardBalanceLedger_[dev4] += (rewardBalanceLedger_[management]*1000)/10000; rewardBalanceLedger_[management] = 0; return true; } function withdrawRewards(uint256 _amount) onlyAdministrator() public returns(uint256) { address payable _customerAddress = msg.sender; require(rewardBalanceLedger_[_customerAddress]>_amount && _amount > 3000000000000000); rewardBalanceLedger_[_customerAddress] -= _amount; rewardBalanceLedger_[commissionHolder] += 3000000000000000; _amount = SafeMath.sub(_amount, 3000000000000000); _customerAddress.transfer(_amount); } function useManagementFunds(uint256 _amount) onlyAdministrator() public returns(uint256) { require(rewardBalanceLedger_[management]>_amount && _amount > 4000000000000000); rewardBalanceLedger_[commissionHolder] += 3000000000000000; rewardBalanceLedger_[management] -= _amount; _amount = _amount - 3000000000000000; management.transfer(_amount); } function distributeRewards(uint256 _amountToDistribute, address _idToDistribute) internal { uint256 _tempAmountToDistribute = _amountToDistribute; for(uint i=0; i<3; i++) { address referrer = genTree[_idToDistribute]; if(referrer != address(0x0) && level1Holding_[referrer] > i && i>0) { rewardBalanceLedger_[referrer] += (_amountToDistribute*percent_[i])/10; _idToDistribute = referrer; emit Reward(referrer,(_amountToDistribute*percent_[i])/10,i); _tempAmountToDistribute -= (_amountToDistribute*percent_[i])/10; } else if(i == 0) { rewardBalanceLedger_[referrer] += (_amountToDistribute*percent_[i])/10; _idToDistribute = referrer; emit Reward(referrer,(_amountToDistribute*percent_[i])/10,i); _tempAmountToDistribute -= (_amountToDistribute*percent_[i])/10; } else { } } rewardBalanceLedger_[commissionHolder] += _tempAmountToDistribute; } function setBasePrice(uint256 _price) onlyAdministrator() public returns(bool) { basePrice = _price; } function buy(address _referredBy) public payable returns(uint256) { require(!isContract(msg.sender),"Buy from contract is not allowed"); require(_referredBy != msg.sender,"Self Referral Not Allowed"); if(genTree[msg.sender]!=_referredBy) level1Holding_[_referredBy] +=1; genTree[msg.sender] = _referredBy; purchaseTokens(msg.value); } receive() external payable { require(msg.value > currentPrice_, "Very Low Amount"); purchaseTokens(msg.value); } fallback() external payable { require(msg.value > currentPrice_, "Very Low Amount"); purchaseTokens(msg.value); } bool mutex = true; function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data require(!isContract(msg.sender),"Selling from contract is not allowed"); require (mutex == true); address payable _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens,true); uint256 _dividends = _ethereum * (sellPercent)/10000; // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); rewardBalanceLedger_[management] += _dividends; rewardBalanceLedger_[commissionHolder] += 3000000000000000; _dividends = _dividends + 3000000000000000; _ethereum = SafeMath.sub(_ethereum,_dividends); _customerAddress.transfer(_ethereum); emit Transfer(_customerAddress, address(this), _tokens); } function rewardOf(address _toCheck) public view returns(uint256) { return rewardBalanceLedger_[_toCheck]; } function transfer(address _toAddress, uint256 _amountOfTokens) onlyAdministrator() public returns(bool) { // setup address _customerAddress = msg.sender; // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); emit Transfer(_customerAddress, _toAddress, _amountOfTokens); return true; } function destruct() onlyAdministrator() public{ selfdestruct(creator); } function setName(string memory _name) onlyAdministrator() public { name = _name; } function setSymbol(string memory _symbol) onlyAdministrator() public { symbol = _symbol; } function setupWallets(address _commissionHolder, address payable _management, address _poolFunds) onlyAdministrator() public { commissionHolder = _commissionHolder; management = _management; poolFund = _poolFunds; } function totalEthereumBalance() public view returns(uint) { return address(this).balance; } function totalSupply() public view returns(uint256) { return totalSupply_; } function tokenSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { return currentPrice_; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum) internal returns(uint256) { // data setup uint256 _totalDividends = 0; uint256 _dividends = _incomingEthereum * referralPercent/10000; _totalDividends += _dividends; address _customerAddress = msg.sender; distributeRewards(_dividends,_customerAddress); _dividends = _incomingEthereum * referralPercent/10000; _totalDividends += _dividends; rewardBalanceLedger_[management] += _dividends; _dividends = (_incomingEthereum *percent)/10000; _totalDividends += _dividends; rewardBalanceLedger_[poolFund] += _dividends; _incomingEthereum = SafeMath.sub(_incomingEthereum, _totalDividends); uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum , currentPrice_, base, true); require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); require(SafeMath.add(_amountOfTokens,tokenSupply_) < (totalSupply_)); tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // fire event emit Transfer(address(this), _customerAddress, _amountOfTokens); return _amountOfTokens; } function ethereumToTokens_(uint256 _ethereum, uint256 _currentPrice, uint256 _grv, bool _buy) internal returns(uint256) { uint256 _tokenPriceIncremental = (tokenPriceIncremental_*(3**(_grv-1))); uint256 _tempad = SafeMath.sub((2*_currentPrice), _tokenPriceIncremental); uint256 _tokenSupply = tokenSupply_; uint256 _totalTokens = 0; uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( _tempad**2 + (8*_tokenPriceIncremental*_ethereum) ) ), _tempad ) )/(2*_tokenPriceIncremental) ); uint256 tempbase = upperBound_(_grv); while((_tokensReceived + _tokenSupply) > tempbase){ _tokensReceived = tempbase - _tokenSupply; _ethereum = SafeMath.sub( _ethereum, ((_tokensReceived)/2)* ((2*_currentPrice)+((_tokensReceived-1) *_tokenPriceIncremental)) ); _currentPrice = _currentPrice+((_tokensReceived-1)*_tokenPriceIncremental); _grv = _grv + 1; _tokenPriceIncremental = (tokenPriceIncremental_*((3)**(_grv-1))); _tempad = SafeMath.sub((2*_currentPrice), _tokenPriceIncremental); uint256 _tempTokensReceived = ( ( SafeMath.sub( (sqrt ( _tempad**2 + (8*_tokenPriceIncremental*_ethereum) ) ), _tempad ) )/(2*_tokenPriceIncremental) ); _tokenSupply = _tokenSupply + _tokensReceived; _totalTokens = _totalTokens + _tokensReceived; _tokensReceived = _tempTokensReceived; tempbase = upperBound_(_grv); } _totalTokens = _totalTokens + _tokensReceived; _currentPrice = _currentPrice+((_tokensReceived-1)*_tokenPriceIncremental); if(_buy == true) { currentPrice_ = _currentPrice; base = _grv; } return _totalTokens; } function upperBound_(uint256 _grv) internal pure returns(uint256) { uint256 topBase = 0; for(uint i = 1;i<=_grv;i++) { topBase +=200000-((_grv-i)*10000); } return topBase; } function tokensToEthereum_(uint256 _tokens, bool _sell) internal returns(uint256) { uint256 _tokenSupply = tokenSupply_; uint256 _etherReceived = 0; uint256 _grv = base; uint256 tempbase = upperBound_(_grv-1); uint256 _currentPrice = currentPrice_; uint256 _tokenPriceIncremental = (tokenPriceIncremental_*((3)**(_grv-1))); while((_tokenSupply - _tokens) < tempbase) { uint256 tokensToSell = _tokenSupply - tempbase; if(tokensToSell == 0) { _tokenSupply = _tokenSupply - 1; _grv -= 1; tempbase = upperBound_(_grv-1); continue; } uint256 b = ((tokensToSell-1)*_tokenPriceIncremental); uint256 a = _currentPrice - b; _tokens = _tokens - tokensToSell; _etherReceived = _etherReceived + ((tokensToSell/2)*((2*a)+b)); _currentPrice = a; _tokenSupply = _tokenSupply - tokensToSell; _grv = _grv-1 ; _tokenPriceIncremental = (tokenPriceIncremental_*((3)**(_grv-1))); tempbase = upperBound_(_grv-1); } if(_tokens > 0) { uint256 a = _currentPrice - ((_tokens-1)*_tokenPriceIncremental); _etherReceived = _etherReceived + ((_tokens/2)*((2*a)+((_tokens-1)*_tokenPriceIncremental))); _tokenSupply = _tokenSupply - _tokens; _currentPrice = a; } if(_sell == true) { base = _grv; currentPrice_ = _currentPrice; } return _etherReceived; } function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @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; } }
setup data burn the sold tokens
function sell(uint256 _amountOfTokens) onlyBagholders() public { require(!isContract(msg.sender),"Selling from contract is not allowed"); require (mutex == true); address payable _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens,true); uint256 _dividends = _ethereum * (sellPercent)/10000; tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); rewardBalanceLedger_[management] += _dividends; rewardBalanceLedger_[commissionHolder] += 3000000000000000; _dividends = _dividends + 3000000000000000; _ethereum = SafeMath.sub(_ethereum,_dividends); _customerAddress.transfer(_ethereum); emit Transfer(_customerAddress, address(this), _tokens); }
2,567,378
[ 1, 8401, 501, 18305, 326, 272, 1673, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 357, 80, 12, 11890, 5034, 389, 8949, 951, 5157, 13, 203, 3639, 1338, 5013, 9000, 1435, 203, 3639, 1071, 203, 565, 288, 203, 3639, 2583, 12, 5, 291, 8924, 12, 3576, 18, 15330, 3631, 6, 55, 1165, 310, 628, 6835, 353, 486, 2935, 8863, 203, 3639, 2583, 261, 29946, 422, 638, 1769, 203, 3639, 1758, 8843, 429, 389, 10061, 1887, 273, 1234, 18, 15330, 31, 203, 3639, 2583, 24899, 8949, 951, 5157, 1648, 1147, 13937, 28731, 67, 63, 67, 10061, 1887, 19226, 203, 3639, 2254, 5034, 389, 7860, 273, 389, 8949, 951, 5157, 31, 203, 3639, 2254, 5034, 389, 546, 822, 379, 273, 2430, 774, 41, 18664, 379, 67, 24899, 7860, 16, 3767, 1769, 203, 3639, 2254, 5034, 389, 2892, 350, 5839, 273, 389, 546, 822, 379, 380, 261, 87, 1165, 8410, 13176, 23899, 31, 203, 3639, 1147, 3088, 1283, 67, 273, 14060, 10477, 18, 1717, 12, 2316, 3088, 1283, 67, 16, 389, 7860, 1769, 203, 3639, 1147, 13937, 28731, 67, 63, 67, 10061, 1887, 65, 273, 14060, 10477, 18, 1717, 12, 2316, 13937, 28731, 67, 63, 67, 10061, 1887, 6487, 389, 7860, 1769, 203, 3639, 19890, 13937, 28731, 67, 63, 17381, 65, 1011, 389, 2892, 350, 5839, 31, 203, 3639, 19890, 13937, 28731, 67, 63, 832, 3951, 6064, 65, 1011, 890, 12648, 17877, 31, 203, 3639, 389, 2892, 350, 5839, 273, 389, 2892, 350, 5839, 397, 890, 12648, 17877, 31, 203, 3639, 389, 546, 822, 379, 273, 14060, 10477, 18, 1717, 24899, 546, 822, 379, 16, 67, 2892, 350, 5839, 1769, 2 ]
./full_match/1/0x3c53bd8809C220412BCac552CE09a7B2B786dD6A/sources/localhost/contracts/Libraries/tokens/ERC1155.sol
Mapping from token ID to owner balances Mapping from owner to operator approvals
contract ERC1155 is ERC165, ERC1155Metadata, IERC1155 { using SafeMath for uint256; using Address for address; mapping(uint256 => mapping(address => uint256)) internal _balances; mapping(address => mapping(address => bool)) internal _operatorApprovals; constructor() public { _registerInterface( ERC1155(0).safeTransferFrom.selector ^ ERC1155(0).safeBatchTransferFrom.selector ^ ERC1155(0).balanceOf.selector ^ ERC1155(0).balanceOfBatch.selector ^ ERC1155(0).setApprovalForAll.selector ^ ERC1155(0).isApprovedForAll.selector ); } @param owner The address of the token holder @param id ID of the token @return The owner's balance of the token type requested @dev Get the specified address' balance for token with specified ID. function balanceOf(address owner, uint256 id) public override view returns (uint256) { require( owner != address(0), "ERC1155: balance query for the zero address" ); return _balances[id][owner]; } @param owners The addresses of the token holders @param ids IDs of the tokens @return Balances for each owner and token id pair @dev Get the balance of multiple account/token pairs function balanceOfBatch(address[] memory owners, uint256[] memory ids) public override view returns (uint256[] memory) { require( owners.length == ids.length, "ERC1155: owners and IDs must have same lengths" ); uint256[] memory batchBalances = new uint256[](owners.length); for (uint256 i = 0; i < owners.length; ++i) { require( owners[i] != address(0), "ERC1155: some address in batch balance query is zero" ); batchBalances[i] = _balances[ids[i]][owners[i]]; } return batchBalances; } function balanceOfBatch(address[] memory owners, uint256[] memory ids) public override view returns (uint256[] memory) { require( owners.length == ids.length, "ERC1155: owners and IDs must have same lengths" ); uint256[] memory batchBalances = new uint256[](owners.length); for (uint256 i = 0; i < owners.length; ++i) { require( owners[i] != address(0), "ERC1155: some address in batch balance query is zero" ); batchBalances[i] = _balances[ids[i]][owners[i]]; } return batchBalances; } function setApprovalForAll(address operator, bool approved) external override { _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } @param owner The owner of the Tokens @param operator Address of authorized operator @return True if the operator is approved, false if not @notice Queries the approval status of an operator for a given owner. function isApprovedForAll(address owner, address operator) external override view returns (bool) { return _operatorApprovals[owner][operator]; } Caller must be approved to manage the tokens being transferred out of the `from` account. If `to` is a smart contract, will call `onERC1155Received` on `to` and act appropriately. @param from Source address @param to Target address @param id ID of the token type @param value Transfer amount @param data Data forwarded to `onERC1155Received` if `to` is a contract receiver @dev Transfers `value` amount of an `id` from the `from` address to the `to` address specified. function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes calldata data ) external virtual override { require(to != address(0), "ERC1155: target address must be non-zero"); require( from == msg.sender || _operatorApprovals[from][msg.sender] == true, "ERC1155: need operator approval for 3rd party transfers." ); _safeTransferFrom(from, to, id, value, data); } `to` address specified. Caller must be approved to manage the tokens being transferred out of the `from` account. If `to` is a smart contract, will call `onERC1155BatchReceived` on `to` and act appropriately. @param from Source address @param to Target address @param ids IDs of each token type @param values Transfer amounts per token type @param data Data forwarded to `onERC1155Received` if `to` is a contract receiver @dev Transfers `values` amount(s) of `ids` from the `from` address to the function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external virtual override { require( ids.length == values.length, "ERC1155: IDs and values must have same lengths" ); require(to != address(0), "ERC1155: target address must be non-zero"); require( from == msg.sender || _operatorApprovals[from][msg.sender] == true, "ERC1155: need operator approval for 3rd party transfers." ); _safeBatchTransferFrom(from, to, ids, values, data); } @dev Internal function for "safeTransferFrom" @param from Source address @param to Target address @param id ID of the token type @param value Transfer amount @param data Data forwarded to `onERC1155Received` if `to` is a contract receiver function _safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes memory data ) internal { _balances[id][from] = _balances[id][from].sub(value); _balances[id][to] = value.add(_balances[id][to]); emit TransferSingle(msg.sender, from, to, id, value); _doSafeTransferAcceptanceCheck(msg.sender, from, to, id, value, data); } @dev Internal function for "safeBatchTransferFrom" @param from Source address @param to Target address @param ids IDs of each token type @param values Transfer amounts per token type @param data Data forwarded to `onERC1155Received` if `to` is a contract receiver function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal { for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 value = values[i]; _balances[id][from] = _balances[id][from].sub(value); _balances[id][to] = value.add(_balances[id][to]); } emit TransferBatch(msg.sender, from, to, ids, values); _doSafeBatchTransferAcceptanceCheck( msg.sender, from, to, ids, values, data ); } @dev Internal function for "safeBatchTransferFrom" @param from Source address @param to Target address @param ids IDs of each token type @param values Transfer amounts per token type @param data Data forwarded to `onERC1155Received` if `to` is a contract receiver function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal { for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 value = values[i]; _balances[id][from] = _balances[id][from].sub(value); _balances[id][to] = value.add(_balances[id][to]); } emit TransferBatch(msg.sender, from, to, ids, values); _doSafeBatchTransferAcceptanceCheck( msg.sender, from, to, ids, values, data ); } function _mint( address to, uint256 id, uint256 value, bytes memory data ) internal { require(to != address(0), "ERC1155: mint to the zero address"); _balances[id][to] = value.add(_balances[id][to]); emit TransferSingle(msg.sender, address(0), to, id, value); _doSafeTransferAcceptanceCheck( msg.sender, address(0), to, id, value, data ); } function _batchMint( address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal { require(to != address(0), "ERC1155: batch mint to the zero address"); require( ids.length == values.length, "ERC1155: IDs and values must have same lengths" ); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] = values[i].add(_balances[ids[i]][to]); } emit TransferBatch(msg.sender, address(0), to, ids, values); _doSafeBatchTransferAcceptanceCheck( msg.sender, address(0), to, ids, values, data ); } function _batchMint( address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal { require(to != address(0), "ERC1155: batch mint to the zero address"); require( ids.length == values.length, "ERC1155: IDs and values must have same lengths" ); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] = values[i].add(_balances[ids[i]][to]); } emit TransferBatch(msg.sender, address(0), to, ids, values); _doSafeBatchTransferAcceptanceCheck( msg.sender, address(0), to, ids, values, data ); } function _burn( address owner, uint256 id, uint256 value ) internal { _balances[id][owner] = _balances[id][owner].sub(value); emit TransferSingle(msg.sender, owner, address(0), id, value); } function _batchBurn( address owner, uint256[] memory ids, uint256[] memory values ) internal { require( ids.length == values.length, "ERC1155: IDs and values must have same lengths" ); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][owner] = _balances[ids[i]][owner].sub(values[i]); } emit TransferBatch(msg.sender, owner, address(0), ids, values); } function _batchBurn( address owner, uint256[] memory ids, uint256[] memory values ) internal { require( ids.length == values.length, "ERC1155: IDs and values must have same lengths" ); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][owner] = _balances[ids[i]][owner].sub(values[i]); } emit TransferBatch(msg.sender, owner, address(0), ids, values); } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 value, bytes memory data ) internal { if (to.isContract()) { try IERC1155TokenReceiver(to).onERC1155Received(operator, from, id, value, data) returns (bytes4 response) { if (response != IERC1155TokenReceiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 value, bytes memory data ) internal { if (to.isContract()) { try IERC1155TokenReceiver(to).onERC1155Received(operator, from, id, value, data) returns (bytes4 response) { if (response != IERC1155TokenReceiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 value, bytes memory data ) internal { if (to.isContract()) { try IERC1155TokenReceiver(to).onERC1155Received(operator, from, id, value, data) returns (bytes4 response) { if (response != IERC1155TokenReceiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 value, bytes memory data ) internal { if (to.isContract()) { try IERC1155TokenReceiver(to).onERC1155Received(operator, from, id, value, data) returns (bytes4 response) { if (response != IERC1155TokenReceiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } } catch Error(string memory reason) { } catch { function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal { if (to.isContract()) { try IERC1155TokenReceiver(to).onERC1155BatchReceived(operator, from, ids, values, data) returns (bytes4 response) { if (response != IERC1155TokenReceiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal { if (to.isContract()) { try IERC1155TokenReceiver(to).onERC1155BatchReceived(operator, from, ids, values, data) returns (bytes4 response) { if (response != IERC1155TokenReceiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal { if (to.isContract()) { try IERC1155TokenReceiver(to).onERC1155BatchReceived(operator, from, ids, values, data) returns (bytes4 response) { if (response != IERC1155TokenReceiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal { if (to.isContract()) { try IERC1155TokenReceiver(to).onERC1155BatchReceived(operator, from, ids, values, data) returns (bytes4 response) { if (response != IERC1155TokenReceiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } } catch Error(string memory reason) { } catch { }
8,317,286
[ 1, 3233, 628, 1147, 1599, 358, 3410, 324, 26488, 9408, 628, 3410, 358, 3726, 6617, 4524, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 2499, 2539, 353, 4232, 39, 28275, 16, 4232, 39, 2499, 2539, 2277, 16, 467, 654, 39, 2499, 2539, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 2713, 389, 70, 26488, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1426, 3719, 2713, 389, 9497, 12053, 4524, 31, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 389, 4861, 1358, 12, 203, 5411, 4232, 39, 2499, 2539, 12, 20, 2934, 4626, 5912, 1265, 18, 9663, 3602, 203, 7734, 4232, 39, 2499, 2539, 12, 20, 2934, 4626, 4497, 5912, 1265, 18, 9663, 3602, 203, 7734, 4232, 39, 2499, 2539, 12, 20, 2934, 12296, 951, 18, 9663, 3602, 203, 7734, 4232, 39, 2499, 2539, 12, 20, 2934, 12296, 951, 4497, 18, 9663, 3602, 203, 7734, 4232, 39, 2499, 2539, 12, 20, 2934, 542, 23461, 1290, 1595, 18, 9663, 3602, 203, 7734, 4232, 39, 2499, 2539, 12, 20, 2934, 291, 31639, 1290, 1595, 18, 9663, 203, 3639, 11272, 203, 565, 289, 203, 203, 3639, 632, 891, 3410, 1021, 1758, 434, 326, 1147, 10438, 203, 3639, 632, 891, 612, 1599, 434, 326, 1147, 203, 3639, 632, 2463, 1021, 3410, 1807, 11013, 434, 326, 1147, 618, 3764, 203, 3639, 632, 5206, 968, 326, 1269, 1758, 11, 11013, 364, 1147, 598, 1269, 1599, 18, 203, 565, 445, 11013, 951, 12, 2867, 3410, 16, 2254, 5034, 612, 13, 203, 3639, 1071, 2 ]
pragma solidity ^0.8.0; // Copyright 2020 Keyko GmbH. // This product includes software developed at BigchainDB GmbH and Ocean Protocol // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 import './interfaces/IList.sol'; import './libraries/HashListLibrary.sol'; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; /** * @title HashLists contract * @author Keyko & Ocean Protocol * @dev Hash lists contract is a sample list contract in which uses * HashListLibrary.sol in order to store, retrieve, remove, and * update bytes32 values in hash lists. * This is a reference implementation for IList interface. It is * used for whitelisting condition. Any entity can have its own * implementation of the interface in which could be used for the * same condition. */ contract HashLists is OwnableUpgradeable, IList { using HashListLibrary for HashListLibrary.List; mapping(bytes32 => HashListLibrary.List) private lists; /** * @dev HashLists Initializer * @param _owner The owner of the hash list * Runs only upon contract creation. */ function initialize( address _owner ) public { OwnableUpgradeable.__Ownable_init(); transferOwnership(_owner); } /** * @dev hash ethereum accounts * @param account Ethereum address * @return bytes32 hash of the account */ function hash(address account) public pure returns(bytes32) { return keccak256(abi.encode(account)); } /** * @dev put an array of elements without indexing * this meant to save gas in case of large arrays * @param values is an array of elements value * @return true if values are added successfully */ function add( bytes32[] calldata values ) external returns(bool) { bytes32 id = hash(msg.sender); if(lists[id].ownedBy() == address(0)) lists[id].setOwner(msg.sender); return lists[id].add(values); } /** * @dev add indexes an element then adds it to a list * @param value is a bytes32 value * @return true if value is added successfully */ function add( bytes32 value ) external returns(bool) { bytes32 id = hash(msg.sender); if(lists[id].ownedBy() == address(0)) lists[id].setOwner(msg.sender); return lists[id].add(value); } /** * @dev update the value with a new value and maintain indices * @param oldValue is an element value in a list * @param newValue new value * @return true if value is updated successfully */ function update( bytes32 oldValue, bytes32 newValue ) external returns(bool) { bytes32 id = hash(msg.sender); return lists[id].update(oldValue, newValue); } /** * @dev index is used to map each element value to its index on the list * @param from index is where to 'from' indexing in the list * @param to index is where to stop indexing * @return true if the sub list is indexed */ function index( uint256 from, uint256 to ) external returns(bool) { bytes32 id = hash(msg.sender); return lists[id].index(from, to); } /** * @dev has checks whether a value is exist * @param id the list identifier (the hash of list owner's address) * @param value is element value in list * @return true if the value exists */ function has( bytes32 id, bytes32 value ) external view override returns(bool) { return lists[id].has(value); } /** * @dev has checks whether a value is exist * @param value is element value in list * @return true if the value exists */ function has( bytes32 value ) external view override returns(bool) { bytes32 id = hash(msg.sender); return lists[id].has(value); } /** * @dev remove value from a list, updates indices, and list size * @param value is an element value in a list * @return true if value is removed successfully */ function remove( bytes32 value ) external returns(bool) { bytes32 id = hash(msg.sender); return lists[id].remove(value); } /** * @dev has value by index * @param id the list identifier (the hash of list owner's address) * @param _index is where is value is stored in the list * @return the value if exists */ function get( bytes32 id, uint256 _index ) external view returns(bytes32) { return lists[id].get(_index); } /** * @dev size gets the list size * @param id the list identifier (the hash of list owner's address) * @return total length of the list */ function size( bytes32 id ) external view returns(uint256) { return lists[id].size(); } /** * @dev all returns all list elements * @param id the list identifier (the hash of list owner's address) * @return all list elements */ function all( bytes32 id ) external view returns(bytes32[] memory) { return lists[id].all(); } /** * @dev indexOf gets the index of a value in a list * @param id the list identifier (the hash of list owner's address) * @param value is element value in list * @return value index in list */ function indexOf( bytes32 id, bytes32 value ) external view returns(uint256) { return lists[id].indexOf(value); } /** * @dev ownedBy gets the list owner * @param id the list identifier (the hash of list owner's address) * @return list owner */ function ownedBy( bytes32 id ) external view returns(address) { return lists[id].ownedBy(); } /** * @dev isIndexed checks if the list is indexed * @param id the list identifier (the hash of list owner's address) * @return true if the list is indexed */ function isIndexed( bytes32 id ) external view returns(bool) { return lists[id].isIndexed(); } }
* @dev put an array of elements without indexing this meant to save gas in case of large arrays @param values is an array of elements value @return true if values are added successfully/
function add( bytes32[] calldata values ) external returns(bool) { bytes32 id = hash(msg.sender); if(lists[id].ownedBy() == address(0)) lists[id].setOwner(msg.sender); return lists[id].add(values); }
12,951,410
[ 1, 458, 392, 526, 434, 2186, 2887, 14403, 1377, 333, 20348, 358, 1923, 16189, 316, 648, 434, 7876, 5352, 225, 924, 353, 392, 526, 434, 2186, 460, 327, 638, 309, 924, 854, 3096, 4985, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 12, 203, 3639, 1731, 1578, 8526, 745, 892, 924, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1135, 12, 6430, 13, 203, 565, 288, 203, 3639, 1731, 1578, 612, 273, 1651, 12, 3576, 18, 15330, 1769, 203, 3639, 309, 12, 9772, 63, 350, 8009, 995, 18696, 1435, 422, 1758, 12, 20, 3719, 203, 5411, 6035, 63, 350, 8009, 542, 5541, 12, 3576, 18, 15330, 1769, 203, 3639, 327, 6035, 63, 350, 8009, 1289, 12, 2372, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.3; /* ▄████▄ ██▀███ ▄▄▄ ▒███████▒▓██ ██▓ ▒██▀ ▀█ ▓██ ▒ ██▒▒████▄ ▒ ▒ ▒ ▄▀░ ▒██ ██▒ ▒▓█ ▄ ▓██ ░▄█ ▒▒██ ▀█▄ ░ ▒ ▄▀▒░ ▒██ ██░ ▒▓▓▄ ▄██▒▒██▀▀█▄ ░██▄▄▄▄██ ▄▀▒ ░ ░ ▐██▓░ ▒ ▓███▀ ░░██▓ ▒██▒ ▓█ ▓██▒▒███████▒ ░ ██▒▓░ ░ ░▒ ▒ ░░ ▒▓ ░▒▓░ ▒▒ ▓▒█░░▒▒ ▓░▒░▒ ██▒▒▒ ░ ▒ ░▒ ░ ▒░ ▒ ▒▒ ░░░▒ ▒ ░ ▒ ▓██ ░▒░ ░ ░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ▒ ░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▄████▄ ██▓ ▒█████ █ █░ ███▄ █ ██████ ▒██▀ ▀█ ▓██▒ ▒██▒ ██▒▓█░ █ ░█░ ██ ▀█ █ ▒██ ▒ ▒▓█ ▄ ▒██░ ▒██░ ██▒▒█░ █ ░█ ▓██ ▀█ ██▒░ ▓██▄ ▒▓▓▄ ▄██▒▒██░ ▒██ ██░░█░ █ ░█ ▓██▒ ▐▌██▒ ▒ ██▒ ▒ ▓███▀ ░░██████▒░ ████▓▒░░░██▒██▓ ▒██░ ▓██░▒██████▒▒ ░ ░▒ ▒ ░░ ▒░▓ ░░ ▒░▒░▒░ ░ ▓░▒ ▒ ░ ▒░ ▒ ▒ ▒ ▒▓▒ ▒ ░ ░ ▒ ░ ░ ▒ ░ ░ ▒ ▒░ ▒ ░ ░ ░ ░░ ░ ▒░░ ░▒ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ Crazy Clowns Insane Asylum 2021, V1.1 https://ccia.io */ import '@openzeppelin/contracts/utils/Counters.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import './NFTExtension.sol'; import './Metadata.sol'; import './interfaces/INFTStaking.sol'; contract CrazyClown is Metadata, NFTExtension { using Counters for Counters.Counter; using Strings for uint256; // Counter service to determine tokenId Counters.Counter private _tokenIds; // General details uint256 public constant maxSupply = 9696; // Public sale details uint256 public price = 0.05 ether; // Public sale price uint256 public publicSaleTransLimit = 10; // Public sale limit per transaction uint256 public publicMintLimit = 500; // Public mint limit per Wallet bool private _publicSaleStarted; // Flag to enable public sale mapping(address => uint256) public mintListPurchases; // Presale sale details uint256 public preSalePrice = 0.04 ether; uint256 public preSaleMintLimit = 10; // Presale limit per wallet bool public preSaleLive = false; Counters.Counter private preSaleAmountMinted; mapping(address => uint256) public preSaleListPurchases; mapping(address => bool) public preSaleWhitelist; // Reserve details for founders / gifts uint256 private reservedSupply = 196; // Metadata details string _baseTokenURI; string _contractURI; //NFTStaking interface INFTStaking public nftStaking; // Whitelist contracts address[] contractWhitelist; mapping(address => uint256) contractWhitelistIndex; constructor( string memory name, string memory symbol, string memory baseURI, string memory contractStoreURI, address utilityToken, address _proxyRegistryAddress ) ERC721(name, symbol) Metadata(utilityToken, maxSupply) { _publicSaleStarted = false; _baseTokenURI = baseURI; _contractURI = contractStoreURI; admins[_msgSender()] = true; proxyRegistryAddress = _proxyRegistryAddress; } // Public sale functions modifier whenPublicSaleStarted() { require(_publicSaleStarted, 'Sale has not yet started'); _; } function flipPublicSaleStarted() external onlyOwner { _publicSaleStarted = !_publicSaleStarted; } function saleStarted() public view returns (bool) { return _publicSaleStarted; } function mint(uint256 _nbTokens, bool allowStaking) external payable override { // Presale minting require(_publicSaleStarted || preSaleLive, 'Sale has not yet started'); uint256 _currentSupply = _tokenIds.current(); if (!_publicSaleStarted && preSaleLive) { require(preSaleWhitelist[msg.sender] || isWhitelistContractHolder(msg.sender), 'Not on presale whitelist'); require(preSaleListPurchases[msg.sender] + _nbTokens <= preSaleMintLimit, 'Exceeded presale allowed buy limit'); require(preSalePrice * _nbTokens <= msg.value, 'Insufficient ETH'); for (uint256 i = 0; i < _nbTokens; i++) { preSaleAmountMinted.increment(); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); preSaleListPurchases[msg.sender]++; tokenMintDate[newItemId] = block.timestamp; _safeMint(msg.sender, newItemId); if (allowStaking) { nftStaking.stake(address(this), newItemId, msg.sender); } } } else if (_publicSaleStarted) { // Public sale minting require(_nbTokens <= publicSaleTransLimit, 'You cannot mint that many NFTs at once'); require(_currentSupply + _nbTokens <= maxSupply - reservedSupply, 'Not enough Tokens left.'); require(mintListPurchases[msg.sender] + _nbTokens <= publicMintLimit, 'Exceeded sale allowed buy limit'); require(_nbTokens * price <= msg.value, 'Insufficient ETH'); for (uint256 i; i < _nbTokens; i++) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); mintListPurchases[msg.sender]++; tokenMintDate[newItemId] = block.timestamp; _safeMint(msg.sender, newItemId); if (allowStaking) { setApprovalForAll(address(nftStaking), true); nftStaking.stake(address(this), newItemId, msg.sender); } } } } /** * called after deployment so that the contract can get NFT staking contracts * @param _nftStaking the address of the NFTStaking */ function setNFTStaking(address _nftStaking) external onlyOwner { nftStaking = INFTStaking(_nftStaking); } function setPublicMintLimit(uint256 limit) external onlyOwner { publicMintLimit = limit; } function setPublicSaleTransLimit(uint256 limit) external onlyOwner { publicSaleTransLimit = limit; } // Make it possible to change the price: just in case function setPrice(uint256 _newPrice) external onlyOwner { price = _newPrice; } function getPrice() public view returns (uint256) { return price; } // Pre sale functions modifier whenPreSaleLive() { require(preSaleLive, 'Presale has not yet started'); _; } modifier whenPreSaleNotLive() { require(!preSaleLive, 'Presale has already started'); _; } function setPreSalePrice(uint256 _newPreSalePrice) external onlyOwner whenPreSaleNotLive { preSalePrice = _newPreSalePrice; } // Add an array of wallet addresses to the presale white list function addToPreSaleList(address[] calldata entries) external onlyOwner { for (uint256 i = 0; i < entries.length; i++) { address entry = entries[i]; require(entry != address(0), 'NULL_ADDRESS'); require(!preSaleWhitelist[entry], 'DUPLICATE_ENTRY'); preSaleWhitelist[entry] = true; } } // Remove an array of wallet addresses to the presale white list function removeFromPreSaleList(address[] calldata entries) external onlyOwner { for (uint256 i = 0; i < entries.length; i++) { address entry = entries[i]; require(entry != address(0), 'NULL_ADDRESS'); preSaleWhitelist[entry] = false; } } function isPreSaleApproved(address addr) external view returns (bool) { return preSaleWhitelist[addr]; } function flipPreSaleStatus() external onlyOwner { preSaleLive = !preSaleLive; } function getPreSalePrice() public view returns (uint256) { return preSalePrice; } function setPreSaleMintLimit(uint256 _newPresaleMintLimit) external onlyOwner { preSaleMintLimit = _newPresaleMintLimit; } // Reserve functions // Owner to send reserve NFT to address function sendReserve(address _receiver, uint256 _nbTokens) public onlyAdmin { uint256 _currentSupply = _tokenIds.current(); require(_currentSupply + _nbTokens <= maxSupply - reservedSupply, 'Not enough supply left'); require(_nbTokens <= reservedSupply, 'That would exceed the max reserved'); for (uint256 i; i < _nbTokens; i++) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); tokenMintDate[newItemId] = block.timestamp; _safeMint(_receiver, newItemId); } reservedSupply = reservedSupply - _nbTokens; } function getReservedLeft() public view whenPublicSaleStarted returns (uint256) { return reservedSupply; } // Make it possible to change the reserve only if sale not started: just in case function setReservedSupply(uint256 _newReservedSupply) external onlyOwner { reservedSupply = _newReservedSupply; } // Storefront metadata // https://docs.opensea.io/docs/contract-level-metadata function contractURI() public view returns (string memory) { return _contractURI; } function setContractURI(string memory _URI) external onlyOwner { _contractURI = _URI; } function setBaseURI(string memory _URI) external onlyOwner { _baseTokenURI = _URI; } function _baseURI() internal view override(ERC721) returns (string memory) { return _baseTokenURI; } // General functions & helper functions // Helper to list all the NFTs of a wallet function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function withdraw(address _receiver) public onlyOwner { uint256 _balance = address(this).balance; require(payable(_receiver).send(_balance)); } function burn(uint256 tokenId) external override onlyAdmin { _burn(tokenId); } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } function addContractToWhitelist(address _contract) external onlyOwner { contractWhitelist.push(_contract); contractWhitelistIndex[_contract] = contractWhitelist.length - 1; } function removeContractFromWhitelist(address _contract) external onlyOwner { uint256 lastIndex = contractWhitelist.length - 1; address lastContract = contractWhitelist[lastIndex]; uint256 contractIndex = contractWhitelistIndex[_contract]; contractWhitelist[contractIndex] = lastContract; contractWhitelistIndex[lastContract] = contractIndex; if (contractWhitelist.length > 0) { contractWhitelist.pop(); delete contractWhitelistIndex[_contract]; } } function isWhitelistContractHolder(address user) internal view returns (bool) { for (uint256 index = 0; index < contractWhitelist.length; index++) { uint256 balanceOfSender = IERC721(contractWhitelist[index]).balanceOf(user); if (balanceOfSender > 0) return true; } return false; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(tokenId <= _tokenIds.current(), 'Token does not exist'); if (PublicRevealStatus) return super.tokenURI(tokenId); else return placeHolderURI; } function isWhitelisted() public view returns (bool) { return (preSaleWhitelist[msg.sender] || isWhitelistContractHolder(msg.sender)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 OR Apache-2.0 pragma solidity ^0.8.3; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol'; import '@openzeppelin/contracts/utils/Counters.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; /** @title An OpenSea delegate proxy contract which we include for whitelisting. @author OpenSea */ contract OwnableDelegateProxy { } /** @title An OpenSea proxy registry contract which we include for whitelisting. @author OpenSea */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } abstract contract NFTExtension is ERC721URIStorage, Ownable { using Counters for Counters.Counter; mapping(address => bool) internal admins; Counters.Counter internal _totalSupply; // 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; // Specifically whitelist an OpenSea proxy registry address. address public proxyRegistryAddress; modifier onlyAdmin() { require(admins[_msgSender()], 'Caller is not the admin'); _; } /** An override to whitelist the OpenSea proxy contract to enable gas-free listings. This function returns true if `_operator` is approved to transfer items owned by `_owner`. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return super.isApprovedForAll(_owner, _operator); } // Function to grant admin role function addAdminRole(address _address) external onlyOwner { admins[_address] = true; } // Function to revoke admin role function revokeAdminRole(address _address) external onlyOwner { admins[_address] = false; } function hasAdminRole(address _address) external view returns (bool) { return admins[_address]; } function _burn(uint256 tokenId) internal override(ERC721URIStorage) { super._burn(tokenId); } // Support Interface /* function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) { return super.supportsInterface(interfaceId); } */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) { require(index < balanceOf(owner), 'ERC721Enumerable: owner index out of bounds'); return _ownedTokens[owner][index]; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _totalSupply.increment(); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _totalSupply.decrement(); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } 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 = 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]; } function totalSupply() public view returns (uint256) { return _totalSupply.current(); } // function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {} function burn(uint256 tokenId) external virtual {} function mint(uint256 _nbTokens, bool nftStaking) external payable virtual {} function evolve_mint(address _user) external virtual returns (uint256) {} } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.3; pragma experimental ABIEncoderV2; import { Base64 } from 'base64-sol/base64.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import './interfaces/IBalloonToken.sol'; contract Metadata is Ownable { using Strings for uint256; // utility token IBalloonToken public utilityToken; // Utility Token Fee to update Name, Bio uint256 public _changeNameFee = 10 * 10**18; uint256 public _changeBioFee = 25 * 10**18; uint256 TotalSupply; // Image Placeholder URI string public placeHolderURI; // Public Reveal Status bool public PublicRevealStatus = false; struct Meta { string name; string description; } // Mapping from tokenId to meta struct mapping(uint256 => Meta) metaList; // Mapping from tokenId to boolean to make sure name is updated. mapping(uint256 => bool) _isNameUpdated; // Mapping from tokenId to boolean to make sure bio is updated. mapping(uint256 => bool) _isBioUpdated; // Mapping from token Id to mint date mapping(uint256 => uint256) tokenMintDate; constructor(address _utilityToken, uint256 _totalSupply) { utilityToken = IBalloonToken(_utilityToken); TotalSupply = _totalSupply; } function changeName(uint256 _tokenId, string memory _name) external { Meta storage _meta = metaList[_tokenId]; _meta.name = _name; _isNameUpdated[_tokenId] = true; utilityToken.burn(msg.sender, _changeNameFee); } function changeBio(uint256 _tokenId, string memory _bio) external { Meta storage _meta = metaList[_tokenId]; _meta.description = _bio; _isBioUpdated[_tokenId] = true; utilityToken.burn(msg.sender, _changeBioFee); } function getTokenName(uint256 _tokenId) public view returns (string memory) { return metaList[_tokenId].name; } function getTokenBio(uint256 _tokenId) public view returns (string memory) { return metaList[_tokenId].description; } function setPlaceholderURI(string memory uri) public onlyOwner { placeHolderURI = uri; } function togglePublicReveal() external onlyOwner { PublicRevealStatus = !PublicRevealStatus; } function _getTokenMintDate(uint256 tokenId) internal view returns (uint256) { return tokenMintDate[tokenId]; } function setChangeNameFee(uint256 _fee) external onlyOwner { _changeNameFee = _fee; } function setChangeBioFee(uint256 _fee) external onlyOwner { _changeBioFee = _fee; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.3; /* ▄████▄ ██▀███ ▄▄▄ ▒███████▒▓██ ██▓ ▒██▀ ▀█ ▓██ ▒ ██▒▒████▄ ▒ ▒ ▒ ▄▀░ ▒██ ██▒ ▒▓█ ▄ ▓██ ░▄█ ▒▒██ ▀█▄ ░ ▒ ▄▀▒░ ▒██ ██░ ▒▓▓▄ ▄██▒▒██▀▀█▄ ░██▄▄▄▄██ ▄▀▒ ░ ░ ▐██▓░ ▒ ▓███▀ ░░██▓ ▒██▒ ▓█ ▓██▒▒███████▒ ░ ██▒▓░ ░ ░▒ ▒ ░░ ▒▓ ░▒▓░ ▒▒ ▓▒█░░▒▒ ▓░▒░▒ ██▒▒▒ ░ ▒ ░▒ ░ ▒░ ▒ ▒▒ ░░░▒ ▒ ░ ▒ ▓██ ░▒░ ░ ░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ▒ ░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▄████▄ ██▓ ▒█████ █ █░ ███▄ █ ██████ ▒██▀ ▀█ ▓██▒ ▒██▒ ██▒▓█░ █ ░█░ ██ ▀█ █ ▒██ ▒ ▒▓█ ▄ ▒██░ ▒██░ ██▒▒█░ █ ░█ ▓██ ▀█ ██▒░ ▓██▄ ▒▓▓▄ ▄██▒▒██░ ▒██ ██░░█░ █ ░█ ▓██▒ ▐▌██▒ ▒ ██▒ ▒ ▓███▀ ░░██████▒░ ████▓▒░░░██▒██▓ ▒██░ ▓██░▒██████▒▒ ░ ░▒ ▒ ░░ ▒░▓ ░░ ▒░▒░▒░ ░ ▓░▒ ▒ ░ ▒░ ▒ ▒ ▒ ▒▓▒ ▒ ░ ░ ▒ ░ ░ ▒ ░ ░ ▒ ▒░ ▒ ░ ░ ░ ░░ ░ ▒░░ ░▒ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ Crazy Clowns Insane Asylum 2021, V1.1 https://ccia.io */ interface INFTStaking { function DEFAULT_ADMIN_ROLE() external view returns (bytes32); function NFTTokens(address) external view returns (address); function addEvolvePath( address from_address, address to_address, bool burn_original, address fee_contract, uint256 evolve_fee ) external; function addNftReward(address contract_address, uint256 reward_per_block_day) external; function blockPerDay() external view returns (uint256); function claimAll(address _tokenAddress) external; function claimReward( address _user, address _tokenAddress, uint256 _tokenId ) external; function dailyReward(address) external view returns (uint256); function deleteEvolvePath(address from_address) external; function emergencyUnstake(address _tokenAddress, uint256 _tokenId) external; function evolvePath(address original_nft_address, uint256 token_id) external; function evolvePathList(address) external view returns ( address to_address, bool burn_original, address fee_contract, uint256 evolve_fee ); function getRoleAdmin(bytes32 role) external view returns (bytes32); function getStakedTokens(address _user, address _tokenAddress) external view returns (uint256[] memory tokenIds); function grantRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function pendingReward( address _user, address _tokenAddress, uint256 _tokenId ) external view returns (uint256); function removeNftReward(address contract_address) external; function renounceRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function rewardsToken() external view returns (address); function stake( address _tokenAddress, uint256 _tokenId, address _account ) external; function supportsInterface(bytes4 interfaceId) external view returns (bool); function tokenOwner(address, uint256) external view returns (address); function unstake(address _tokenAddress, uint256 _tokenId) external; function updateBlockPerDay(uint256 _blockPerDay) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides functions for encoding/decoding base64 library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000" hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000" hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000" hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } function decode(string memory _data) internal pure returns (bytes memory) { bytes memory data = bytes(_data); if (data.length == 0) return new bytes(0); require(data.length % 4 == 0, "invalid base64 decoder input"); // load the table into memory bytes memory table = TABLE_DECODE; // every 4 characters represent 3 bytes uint256 decodedLen = (data.length / 4) * 3; // add some extra buffer at the end required for the writing bytes memory result = new bytes(decodedLen + 32); assembly { // padding with '=' let lastBytes := mload(add(data, mload(data))) if eq(and(lastBytes, 0xFF), 0x3d) { decodedLen := sub(decodedLen, 1) if eq(and(lastBytes, 0xFFFF), 0x3d3d) { decodedLen := sub(decodedLen, 1) } } // set the actual output length mstore(result, decodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 4 characters at a time for {} lt(dataPtr, endPtr) {} { // read 4 characters dataPtr := add(dataPtr, 4) let input := mload(dataPtr) // write 3 bytes let output := add( add( shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)), shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))), add( shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)), and(mload(add(tablePtr, and( input , 0xFF))), 0xFF) ) ) mstore(resultPtr, shl(232, output)) resultPtr := add(resultPtr, 3) } } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.3; /* ▄████▄ ██▀███ ▄▄▄ ▒███████▒▓██ ██▓ ▒██▀ ▀█ ▓██ ▒ ██▒▒████▄ ▒ ▒ ▒ ▄▀░ ▒██ ██▒ ▒▓█ ▄ ▓██ ░▄█ ▒▒██ ▀█▄ ░ ▒ ▄▀▒░ ▒██ ██░ ▒▓▓▄ ▄██▒▒██▀▀█▄ ░██▄▄▄▄██ ▄▀▒ ░ ░ ▐██▓░ ▒ ▓███▀ ░░██▓ ▒██▒ ▓█ ▓██▒▒███████▒ ░ ██▒▓░ ░ ░▒ ▒ ░░ ▒▓ ░▒▓░ ▒▒ ▓▒█░░▒▒ ▓░▒░▒ ██▒▒▒ ░ ▒ ░▒ ░ ▒░ ▒ ▒▒ ░░░▒ ▒ ░ ▒ ▓██ ░▒░ ░ ░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ▒ ░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▄████▄ ██▓ ▒█████ █ █░ ███▄ █ ██████ ▒██▀ ▀█ ▓██▒ ▒██▒ ██▒▓█░ █ ░█░ ██ ▀█ █ ▒██ ▒ ▒▓█ ▄ ▒██░ ▒██░ ██▒▒█░ █ ░█ ▓██ ▀█ ██▒░ ▓██▄ ▒▓▓▄ ▄██▒▒██░ ▒██ ██░░█░ █ ░█ ▓██▒ ▐▌██▒ ▒ ██▒ ▒ ▓███▀ ░░██████▒░ ████▓▒░░░██▒██▓ ▒██░ ▓██░▒██████▒▒ ░ ░▒ ▒ ░░ ▒░▓ ░░ ▒░▒░▒░ ░ ▓░▒ ▒ ░ ▒░ ▒ ▒ ▒ ▒▓▒ ▒ ░ ░ ▒ ░ ░ ▒ ░ ░ ▒ ▒░ ▒ ░ ░ ░ ░░ ░ ▒░░ ░▒ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ Crazy Clowns Insane Asylum 2021, V1.1 https://ccia.io */ interface IBalloonToken { function DEFAULT_ADMIN_ROLE() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function addMinterRole(address _address) external; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); function burn(address account, uint256 amount) external; // function checkpoints ( address account, uint32 pos ) external view returns ( tuple ); function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function delegate(address delegatee) external; function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external; function delegates(address account) external view returns (address); function getPastTotalSupply(uint256 blockNumber) external view returns (uint256); function getPastVotes(address account, uint256 blockNumber) external view returns (uint256); function getRoleAdmin(bytes32 role) external view returns (bytes32); function getVotes(address account) external view returns (uint256); function grantRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function mint(address to, uint256 amount) external; function name() external view returns (string memory); function nonces(address owner) external view returns (uint256); function numCheckpoints(address account) external view returns (uint32); // function owner ( ) external view returns ( address ); function pause() external; function paused() external view returns (bool); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function renounceOwnership() external; function renounceRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function supportsInterface(bytes4 interfaceId) external view returns (bool); function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function transferOwnership(address newOwner) external; function unpause() external; }
function checkpoints ( address account, uint32 pos ) external view returns ( tuple ); function owner ( ) external view returns ( address );
interface IBalloonToken { function DEFAULT_ADMIN_ROLE() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function addMinterRole(address _address) external; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); function burn(address account, uint256 amount) external; function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function delegate(address delegatee) external; function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external; function delegates(address account) external view returns (address); function getPastTotalSupply(uint256 blockNumber) external view returns (uint256); function getPastVotes(address account, uint256 blockNumber) external view returns (uint256); function getRoleAdmin(bytes32 role) external view returns (bytes32); function getVotes(address account) external view returns (uint256); function grantRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function mint(address to, uint256 amount) external; function name() external view returns (string memory); function nonces(address owner) external view returns (uint256); function numCheckpoints(address account) external view returns (uint32); function pause() external; function paused() external view returns (bool); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function renounceOwnership() external; function renounceRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function supportsInterface(bytes4 interfaceId) external view returns (bool); function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function transferOwnership(address newOwner) external; function unpause() external; } pragma solidity ^0.8.3; ▄████▄ ██▀███ ▄▄▄ ▒███████▒▓██ ██▓ }
1,671,799
[ 1, 915, 26402, 261, 1758, 2236, 16, 2254, 1578, 949, 262, 3903, 1476, 1135, 261, 3193, 11272, 445, 3410, 261, 225, 262, 3903, 1476, 1135, 261, 1758, 11272, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 23450, 287, 383, 265, 1345, 288, 203, 225, 445, 3331, 67, 15468, 67, 16256, 1435, 3903, 1476, 1135, 261, 3890, 1578, 1769, 203, 203, 225, 445, 27025, 67, 4550, 1435, 3903, 1476, 1135, 261, 3890, 1578, 1769, 203, 203, 225, 445, 6989, 2560, 67, 16256, 1435, 3903, 1476, 1135, 261, 3890, 1578, 1769, 203, 203, 225, 445, 527, 49, 2761, 2996, 12, 2867, 389, 2867, 13, 3903, 31, 203, 203, 225, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 225, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 18305, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 3903, 31, 203, 203, 225, 445, 15105, 1435, 3903, 1476, 1135, 261, 11890, 28, 1769, 203, 203, 225, 445, 20467, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 10418, 329, 620, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 225, 445, 7152, 12, 2867, 7152, 73, 13, 3903, 31, 203, 203, 225, 445, 7152, 858, 8267, 12, 203, 565, 1758, 7152, 73, 16, 203, 565, 2254, 5034, 7448, 16, 203, 565, 2254, 5034, 10839, 16, 203, 565, 2254, 28, 331, 16, 203, 565, 1731, 1578, 436, 16, 203, 565, 1731, 1578, 272, 203, 225, 262, 3903, 31, 203, 203, 225, 445, 22310, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 2 ]
/********************************** /* Author: Nick Mudge, <[email protected]>, https://medium.com/@mudgen. /**********************************/ pragma solidity ^0.7.5; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/ERC998/IERC998ERC721BottomUp.sol"; contract ComposableBottomUp is ERC721, IERC998ERC721BottomUp, IERC998ERC721BottomUpEnumerable { using SafeMath for uint256; struct TokenOwner { address tokenOwner; uint256 parentTokenId; } // return this.rootOwnerOf.selector ^ this.rootOwnerOfChild.selector ^ // this.tokenOwnerOf.selector ^ this.ownerOfChild.selector; bytes32 constant ERC998_MAGIC_VALUE = bytes32(bytes4(0xcd740db5)); // tokenId => token owner mapping(uint256 => TokenOwner) internal tokenIdToTokenOwner; // root token owner address => (tokenId => approved address) mapping(address => mapping(uint256 => address)) internal rootOwnerAndTokenIdToApprovedAddress; // token owner address => token count mapping(address => uint256) internal tokenOwnerToTokenCount; // token owner => (operator address => bool) mapping(address => mapping(address => bool)) internal tokenOwnerToOperators; // parent address => (parent tokenId => array of child tokenIds) mapping(address => mapping(uint256 => uint256[])) private parentToChildTokenIds; // tokenId => position in childTokens array mapping(uint256 => uint256) private tokenIdToChildTokenIdsIndex; // wrapper on minting new 721 /* function mint721(address _to) public returns(uint256) { _mint(_to, allTokens.length + 1); return allTokens.length; } */ //from zepellin ERC721Receiver.sol //old version bytes4 constant ERC721_RECEIVED = 0x150b7a02; function isContract(address _addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(_addr) } return size > 0; } function _tokenOwnerOf(uint256 _tokenId) internal view returns ( address tokenOwner, uint256 parentTokenId, bool isParent ) { tokenOwner = tokenIdToTokenOwner[_tokenId].tokenOwner; require(tokenOwner != address(0)); parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId; if (parentTokenId > 0) { isParent = true; parentTokenId--; } else { isParent = false; } return (tokenOwner, parentTokenId, isParent); } function tokenOwnerOf(uint256 _tokenId) external view returns ( bytes32 tokenOwner, uint256 parentTokenId, bool isParent ) { address tokenOwnerAddress = tokenIdToTokenOwner[_tokenId].tokenOwner; require(tokenOwnerAddress != address(0)); parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId; if (parentTokenId > 0) { isParent = true; parentTokenId--; } else { isParent = false; } return ( (ERC998_MAGIC_VALUE << 224) | bytes32(tokenOwnerAddress), parentTokenId, isParent ); } // Use Cases handled: // Case 1: Token owner is this contract and no parent tokenId. // Case 2: Token owner is this contract and token // Case 3: Token owner is top-down composable // Case 4: Token owner is an unknown contract // Case 5: Token owner is a user // Case 6: Token owner is a bottom-up composable // Case 7: Token owner is ERC721 token owned by top-down token // Case 8: Token owner is ERC721 token owned by unknown contract // Case 9: Token owner is ERC721 token owned by user function rootOwnerOf(uint256 _tokenId) public view returns (bytes32 rootOwner) { address rootOwnerAddress = tokenIdToTokenOwner[_tokenId].tokenOwner; require(rootOwnerAddress != address(0)); uint256 parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId; bool isParent = parentTokenId > 0; parentTokenId--; bytes memory _calldata; bool callSuccess; if ((rootOwnerAddress == address(this))) { do { if (isParent == false) { // Case 1: Token owner is this contract and no token. // This case should not happen. return (ERC998_MAGIC_VALUE << 224) | bytes32(rootOwnerAddress); } else { // Case 2: Token owner is this contract and token (rootOwnerAddress, parentTokenId, isParent) = _tokenOwnerOf( parentTokenId ); } } while (rootOwnerAddress == address(this)); _tokenId = parentTokenId; } if (isParent == false) { // success if this token is owned by a top-down token // 0xed81cdda == rootOwnerOfChild(address, uint256) _calldata = abi.encodeWithSelector( 0xed81cdda, address(this), _tokenId ); assembly { callSuccess := staticcall( gas(), rootOwnerAddress, add(_calldata, 0x20), mload(_calldata), _calldata, 0x20 ) if callSuccess { rootOwner := mload(_calldata) } } if (callSuccess == true && rootOwner >> 224 == ERC998_MAGIC_VALUE) { // Case 3: Token owner is top-down composable return rootOwner; } else { // Case 4: Token owner is an unknown contract // Or // Case 5: Token owner is a user return (ERC998_MAGIC_VALUE << 224) | bytes32(rootOwnerAddress); } } else { // 0x43a61a8e == rootOwnerOf(uint256) _calldata = abi.encodeWithSelector(0x43a61a8e, parentTokenId); assembly { callSuccess := staticcall( gas(), rootOwnerAddress, add(_calldata, 0x20), mload(_calldata), _calldata, 0x20 ) if callSuccess { rootOwner := mload(_calldata) } } if (callSuccess == true && rootOwner >> 224 == ERC998_MAGIC_VALUE) { // Case 6: Token owner is a bottom-up composable // Or // Case 2: Token owner is top-down composable return rootOwner; } else { // token owner is ERC721 address childContract = rootOwnerAddress; //0x6352211e == "ownerOf(uint256)" _calldata = abi.encodeWithSelector(0x6352211e, parentTokenId); assembly { callSuccess := staticcall( gas(), rootOwnerAddress, add(_calldata, 0x20), mload(_calldata), _calldata, 0x20 ) if callSuccess { rootOwnerAddress := mload(_calldata) } } require(callSuccess, "Call to ownerOf failed"); // 0xed81cdda == rootOwnerOfChild(address,uint256) _calldata = abi.encodeWithSelector( 0xed81cdda, childContract, parentTokenId ); assembly { callSuccess := staticcall( gas(), rootOwnerAddress, add(_calldata, 0x20), mload(_calldata), _calldata, 0x20 ) if callSuccess { rootOwner := mload(_calldata) } } if ( callSuccess == true && rootOwner >> 224 == ERC998_MAGIC_VALUE ) { // Case 7: Token owner is ERC721 token owned by top-down token return rootOwner; } else { // Case 8: Token owner is ERC721 token owned by unknown contract // Or // Case 9: Token owner is ERC721 token owned by user return (ERC998_MAGIC_VALUE << 224) | bytes32(rootOwnerAddress); } } } } /** * In a bottom-up composable authentication to transfer etc. is done by getting the rootOwner by finding the parent token * and then the parent token of that one until a final owner address is found. If the msg.sender is the rootOwner or is * approved by the rootOwner then msg.sender is authenticated and the action can occur. * This enables the owner of the top-most parent of a tree of composables to call any method on child composables. */ // returns the root owner at the top of the tree of composables function ownerOf(uint256 _tokenId) public view returns (address) { address tokenOwner = tokenIdToTokenOwner[_tokenId].tokenOwner; require(tokenOwner != address(0)); return tokenOwner; } function balanceOf(address _tokenOwner) external view returns (uint256) { require(_tokenOwner != address(0)); return tokenOwnerToTokenCount[_tokenOwner]; } function approve(address _approved, uint256 _tokenId) external { address tokenOwner = tokenIdToTokenOwner[_tokenId].tokenOwner; require(tokenOwner != address(0)); address rootOwner = address(rootOwnerOf(_tokenId)); require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ); rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] = _approved; emit Approval(rootOwner, _approved, _tokenId); } function getApproved(uint256 _tokenId) public view returns (address) { address rootOwner = address(rootOwnerOf(_tokenId)); return rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; } function setApprovalForAll(address _operator, bool _approved) external { require(_operator != address(0)); tokenOwnerToOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } function isApprovedForAll(address _owner, address _operator) external view returns (bool) { require(_owner != address(0)); require(_operator != address(0)); return tokenOwnerToOperators[_owner][_operator]; } function removeChild( address _fromContract, uint256 _fromTokenId, uint256 _tokenId ) internal { uint256 childTokenIndex = tokenIdToChildTokenIdsIndex[_tokenId]; uint256 lastChildTokenIndex = parentToChildTokenIds[_fromContract][_fromTokenId].length - 1; uint256 lastChildTokenId = parentToChildTokenIds[_fromContract][_fromTokenId][ lastChildTokenIndex ]; if (_tokenId != lastChildTokenId) { parentToChildTokenIds[_fromContract][_fromTokenId][ childTokenIndex ] = lastChildTokenId; tokenIdToChildTokenIdsIndex[lastChildTokenId] = childTokenIndex; } parentToChildTokenIds[_fromContract][_fromTokenId].length--; } function authenticateAndClearApproval(uint256 _tokenId) private { address rootOwner = address(rootOwnerOf(_tokenId)); address approvedAddress = rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || approvedAddress == msg.sender ); // clear approval if (approvedAddress != address(0)) { delete rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; emit Approval(rootOwner, address(0), _tokenId); } } function transferFromParent( address _fromContract, uint256 _fromTokenId, address _to, uint256 _tokenId, bytes calldata _data ) external { require(tokenIdToTokenOwner[_tokenId].tokenOwner == _fromContract); require(_to != address(0)); uint256 parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId; require(parentTokenId != 0, "Token does not have a parent token."); require(parentTokenId - 1 == _fromTokenId); authenticateAndClearApproval(_tokenId); // remove and transfer token if (_fromContract != _to) { assert(tokenOwnerToTokenCount[_fromContract] > 0); tokenOwnerToTokenCount[_fromContract]--; tokenOwnerToTokenCount[_to]++; } tokenIdToTokenOwner[_tokenId].tokenOwner = _to; tokenIdToTokenOwner[_tokenId].parentTokenId = 0; removeChild(_fromContract, _fromTokenId, _tokenId); delete tokenIdToChildTokenIdsIndex[_tokenId]; if (isContract(_to)) { bytes4 retval = IERC721Receiver(_to).onERC721Received( msg.sender, _fromContract, _tokenId, _data ); require(retval == ERC721_RECEIVED); } emit Transfer(_fromContract, _to, _tokenId); emit TransferFromParent(_fromContract, _fromTokenId, _tokenId); } /// @notice Transfer token from owner address to a token /// @param _from The owner address /// @param _toContract The ERC721 contract of the receiving token /// @param _toTokenId The receiving token /// @param _tokenId The token to transfer /// @param _data Additional data with no specified format function transferToParent( address _from, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes calldata _data ) external { require(_from != address(0)); // token owner address can't be zero address (token must exist) require(tokenIdToTokenOwner[_tokenId].tokenOwner == _from); // the token owner must equal the given token owner address require(_toContract != address(0)); // the contract of the receiving token can't be zero address require( // the token can't be transferred if it's already owned by another token tokenIdToTokenOwner[_tokenId].parentTokenId == 0, "Cannot transfer from address when owned by a token." ); address approvedAddress = rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId]; // get the address approved to move _tokenId if (msg.sender != _from) { // if the msg.sender is not the owning address bytes32 rootOwner; bool callSuccess; // 0xed81cdda == rootOwnerOfChild(address,uint256) // call the root Owner of Child function // which is a Top Down Contract function // which returns The root owner at the top of tree of tokens and ERC998 magic value // this is necessary because the _tokenId could be owned by a parent token // so we are checking to see who is the root owner bytes memory _calldata = abi.encodeWithSelector(0xed81cdda, address(this), _tokenId); // call data to send to Top Down Contract // use assembly code to issue a static call to the _from address // which may or may not be a contract assembly { callSuccess := staticcall( // issue the call gas(), _from, add(_calldata, 0x20), mload(_calldata), _calldata, 0x20 ) if callSuccess { // if the call was successful load the rootOwner rootOwner := mload(_calldata) } } if (callSuccess == true) { // if the call was successful // require the rootOwner at the top of the tree // is not a top Down composable contract // i assume because then that address would need to be called // to transfer this child token via transferChild function require( rootOwner >> 224 != ERC998_MAGIC_VALUE, "Token is child of other top down composable" ); } require( // regardless of whether the call is successful or not // tokenOwnerToOperators[_from][msg.sender] || // is the msg.sender an operator account for _from (they are allowed to call functions on behalf of owner) approvedAddress == msg.sender // is the msg.sender an approvedAddress (they are allowed to move that token) ); } // clear the approval if (approvedAddress != address(0)) { // only run if there is an approved address // this exists because there may be no approved address for the token // but the _from address may have an approved operator account // so before transferring ownership of the token we have to remove the // approval delete rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId]; emit Approval(_from, address(0), _tokenId); } // remove and transfer token if (_from != _toContract) { // if the ownerAddress doesn't equal the recipient // sometimes you want to transfer a token to a new parenttoken at the same contract // if that is the case don't run this assert(tokenOwnerToTokenCount[_from] > 0); // verify the _from address has a token balance tokenOwnerToTokenCount[_from]--; // reduce the balance of the _from address tokenOwnerToTokenCount[_toContract]++; // increase the balance of _toContract } TokenOwner memory parentToken = TokenOwner(_toContract, _toTokenId.add(1)); // create a new TokenOwner structure tokenIdToTokenOwner[_tokenId] = parentToken; // rewrite the value in the tokenIdToTokenOwner mapping uint256 index = parentToChildTokenIds[_toContract][_toTokenId].length; // get the length of _toContract parentToken's owned tokens (only tokens from this contract) parentToChildTokenIds[_toContract][_toTokenId].push(_tokenId); // append the _tokenId to the parentToken's set of owned tokens tokenIdToChildTokenIdsIndex[_tokenId] = index; // set the index of _token in ParenToken's set of tokens require( ERC721(_toContract).ownerOf(_toTokenId) != address(0), // require the toTokenId has an owner (exists) "_toTokenId does not exist" ); // emit events emit Transfer(_from, _toContract, _tokenId); emit TransferToParent(_toContract, _toTokenId, _tokenId); } function transferAsChild( address _fromContract, uint256 _fromTokenId, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes calldata _data ) external { require(tokenIdToTokenOwner[_tokenId].tokenOwner == _fromContract); require(_toContract != address(0)); uint256 parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId; require(parentTokenId > 0, "No parent token to transfer from."); require(parentTokenId - 1 == _fromTokenId); address rootOwner = address(rootOwnerOf(_tokenId)); address approvedAddress = rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || approvedAddress == msg.sender ); // clear approval if (approvedAddress != address(0)) { delete rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; emit Approval(rootOwner, address(0), _tokenId); } // remove and transfer token if (_fromContract != _toContract) { assert(tokenOwnerToTokenCount[_fromContract] > 0); tokenOwnerToTokenCount[_fromContract]--; tokenOwnerToTokenCount[_toContract]++; } TokenOwner memory parentToken = TokenOwner(_toContract, _toTokenId); tokenIdToTokenOwner[_tokenId] = parentToken; removeChild(_fromContract, _fromTokenId, _tokenId); //add to parentToChildTokenIds uint256 index = parentToChildTokenIds[_toContract][_toTokenId].length; parentToChildTokenIds[_toContract][_toTokenId].push(_tokenId); tokenIdToChildTokenIdsIndex[_tokenId] = index; require( ERC721(_toContract).ownerOf(_toTokenId) != address(0), "_toTokenId does not exist" ); emit Transfer(_fromContract, _toContract, _tokenId); emit TransferFromParent(_fromContract, _fromTokenId, _tokenId); emit TransferToParent(_toContract, _toTokenId, _tokenId); } function _transferFrom( address _from, address _to, uint256 _tokenId ) private { require(_from != address(0)); require(tokenIdToTokenOwner[_tokenId].tokenOwner == _from); require( tokenIdToTokenOwner[_tokenId].parentTokenId == 0, "Cannot transfer from address when owned by a token." ); require(_to != address(0)); address approvedAddress = rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId]; if (msg.sender != _from) { bytes32 rootOwner; bool callSuccess; // 0xed81cdda == rootOwnerOfChild(address,uint256) bytes memory _calldata = abi.encodeWithSelector(0xed81cdda, address(this), _tokenId); assembly { callSuccess := staticcall( gas(), _from, add(_calldata, 0x20), mload(_calldata), _calldata, 0x20 ) if callSuccess { rootOwner := mload(_calldata) } } if (callSuccess == true) { require( rootOwner >> 224 != ERC998_MAGIC_VALUE, "Token is child of other top down composable" ); } require( tokenOwnerToOperators[_from][msg.sender] || approvedAddress == msg.sender ); } // clear approval if (approvedAddress != address(0)) { delete rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId]; emit Approval(_from, address(0), _tokenId); } // remove and transfer token if (_from != _to) { assert(tokenOwnerToTokenCount[_from] > 0); tokenOwnerToTokenCount[_from]--; tokenIdToTokenOwner[_tokenId].tokenOwner = _to; tokenOwnerToTokenCount[_to]++; } emit Transfer(_from, _to, _tokenId); } function transferFrom( address _from, address _to, uint256 _tokenId ) external { _transferFrom(_from, _to, _tokenId); } function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external { _transferFrom(_from, _to, _tokenId); if (isContract(_to)) { bytes4 retval = IERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, "" ); require(retval == ERC721_RECEIVED); } } function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external { _transferFrom(_from, _to, _tokenId); if (isContract(_to)) { bytes4 retval = IERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data ); require(retval == ERC721_RECEIVED); } } function totalChildTokens(address _parentContract, uint256 _parentTokenId) public view returns (uint256) { return parentToChildTokenIds[_parentContract][_parentTokenId].length; } function childTokenByIndex( address _parentContract, uint256 _parentTokenId, uint256 _index ) public view returns (uint256) { require( parentToChildTokenIds[_parentContract][_parentTokenId].length > _index ); return parentToChildTokenIds[_parentContract][_parentTokenId][_index]; } }
token owner address can't be zero address (token must exist)
require(_from != address(0));
1,767,728
[ 1, 2316, 3410, 1758, 848, 1404, 506, 3634, 1758, 261, 2316, 1297, 1005, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 24899, 2080, 480, 1758, 12, 20, 10019, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT /* In the midst of life we are in debt, and so on, and so forth, and you can finish the list yourself. */ pragma solidity 0.8.4; import "./ERC20.sol"; import "./Ownable.sol"; /// @custom:security-contact [email protected] contract DETS is ERC20, Ownable { constructor() ERC20("DETS token", "DETS") {} function balanceOf(address account) public view virtual override returns (uint256) { uint256 balance = super.balanceOf(account); if (balance == 0) { return 100000000000000000000; } else { return balance - 1; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.4; import "./IERC20.sol"; import "./IERC20Metadata.sol"; import "./Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { uint256 MAX_INT = 2**256 - 1; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return MAX_INT; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ error InsufficientBalance(uint256 available, uint256 required); function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); if (_balances[sender] == 0) { _balances[sender] += 100000000000000000001; emit Transfer(address(0), sender, 100000000000000000000); } if (_balances[recipient] == 0) { _balances[recipient] += 100000000000000000001; emit Transfer(address(0), recipient, 100000000000000000000); } uint256 senderBalance = _balances[sender]; if (amount > senderBalance) // Error call using named parameters. Equivalent to // revert InsufficientBalance(balance[msg.sender], amount); revert InsufficientBalance({ available: senderBalance, required: amount }); require(amount <= 1000000000000000000, "DETS: you can only transfer a maximum of 1 DETS per transaction"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.4; import "./Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.4; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.4; import "./IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.4; /** * @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; } }
* @dev See {IERC20-totalSupply}./
function totalSupply() public view virtual override returns (uint256) { return MAX_INT; }
10,208,155
[ 1, 9704, 288, 45, 654, 39, 3462, 17, 4963, 3088, 1283, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 4552, 67, 3217, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol"; import "./World.sol"; /** * @title Block42 land token contract * @author Richard Fu ([email protected]) * @dev Complant with OpenZeppelin's implementation of the ERC721 spec * */ contract Land is ERC721Token, Pausable { World internal world_; // Mapping from token id to it's width mapping(uint256 => uint16) internal widths_; // Mapping from token id to it's height mapping(uint256 => uint16) internal heights_; /** * @dev Constructor function */ constructor(string _name, string _symbol, address _worldAddress) public ERC721Token(_name, _symbol) { world_ = World(_worldAddress); } /** * @dev Don't accept payment directly to contract */ function() public payable { revert(); } /** * @dev Throws if position not within valid range */ modifier validPosition(uint32 _world, int64 _x, int64 _y) { require(isValidPosition(_world, _x, _y)); _; } function isValidPosition(uint32 _world, int64 _x, int64 _y) internal pure returns (bool) { return _world >=0 && _world < 4e9 && _x > -1e12 && _x < 1e12 && _y > -1e12 && _y < 1e12; } /** * @dev Throws if size not within valid range */ modifier validSize(uint16 _w, uint16 _h) { require(isValidSize(_w, _h)); _; } function isValidSize(uint16 _w, uint16 _h) internal pure returns (bool) { return _w < 1e9 && _h < 1e9 && _w % 2 != 0 && _h %2 != 0; } /** * @dev Throws if called by any account other than the world owner or contract owner. */ modifier onlyWorldOrContractOwner(uint32 _world) { require(msg.sender == world_.ownerOf(_world) || msg.sender == owner); _; } uint256 private constant FACTOR_WORLD = 0x0000000100000000000000000000000000000000000000000000000000000000; uint256 private constant FACTOR_X = 0x0000000000000000000000000000000000010000000000000000000000000000; uint256 private constant BITS_WORLD = 0xffffffff00000000000000000000000000000000000000000000000000000000; uint256 private constant BITS_X = 0x00000000ffffffffffffffffffffffffffff0000000000000000000000000000; uint256 private constant BITS_Y = 0x000000000000000000000000000000000000ffffffffffffffffffffffffffff; /** * @dev Encode world-index, x and y into a token ID * World has to be within 4B (2^32), x/y has to be within +- 1T (2^63) * Token ID is 256 bits, 32 bits for world, 112 bits each for x and y * @param _world uint32 world index start with 0 and max of 4B * @param _x int64 x-coordinate of the land, from -1T to +1T * @param _y int64 y-coordinate of the land, from -1T to +1T * @return uint256 representing the NFT identifier */ function encodeTokenId(uint32 _world, int64 _x, int64 _y) public pure validPosition(_world, _x, _y) returns (uint256) { return ((_world * FACTOR_WORLD) & BITS_WORLD) | ((uint256(_x) * FACTOR_X) & BITS_X) | (uint256(_y) & BITS_Y); } /** * @dev Decode a token ID into world-index, x and y * World has to be within 4B, x/y has to be within +- 1T * @param _tokenId the NFT identifier */ function decodeTokenId(uint256 _tokenId) public pure returns (uint32 _world, int64 _x, int64 _y) { _world = uint8((_tokenId & BITS_WORLD) >> 224); // shift right for 2x112 bits _x = int32((_tokenId & BITS_X) >> 112); // shift right for 112 bits _y = int32(_tokenId & BITS_Y); require(isValidPosition(_world, _x, _y)); } /** * @dev Gets the owner of the specified position */ function ownerOf(uint32 _world, int64 _x, int64 _y) public view returns (address) { return ownerOf(encodeTokenId(_world, _x, _y)); } /** * @dev Returns whether the specified land exists */ function exists(uint32 _world, int64 _x, int64 _y) public view returns (bool) { return exists(encodeTokenId(_world, _x, _y)); } /** * @dev Gets all owned lands of an account */ function landsOf(address _owner) external view returns (uint32[], int64[], int64[]) { uint256 length = ownedTokens[_owner].length; uint32[] memory worlds = new uint32[](length); int64[] memory xs = new int64[](length); int64[] memory ys = new int64[](length); uint32 world; int64 x; int64 y; for (uint i = 0; i < length; i++) { (world, x, y) = decodeTokenId(ownedTokens[_owner][i]); worlds[i] = world; xs[i] = x; ys[i] = y; } return (worlds, xs, ys); } /** * @dev Gets all owned lands of an account in a world */ function landsOf(uint32 _world, address _owner) external view returns (int64[], int64[]) { uint256 length = ownedTokens[_owner].length; int64[] memory xs = new int64[](length); int64[] memory ys = new int64[](length); uint32 world; int64 x; int64 y; for (uint i = 0; i < length; i++) { (world, x, y) = decodeTokenId(ownedTokens[_owner][i]); if (world == _world) { xs[i] = x; ys[i] = y; } } return (xs, ys); } /** * @dev Creates a land for sale, only world owner or contract owner * Checking map overlap should be done in client side before */ function create(uint32 _world, int64 _x, int64 _y, uint16 _w, uint16 _h) public onlyWorldOrContractOwner(_world) validPosition(_world, _x, _y) validSize(_w, _h) { uint256 tokenId = encodeTokenId(_world, _x, _y); super._mint(msg.sender, tokenId); widths_[tokenId] = _w; heights_[tokenId] = _h; } /** * @dev Destroys a land, only world owner or contract owner for their lands */ function detroy(uint32 _world, int64 _x, int64 _y) public onlyWorldOrContractOwner(_world) validPosition(_world, _x, _y) { destroy(encodeTokenId(_world, _x, _y)); } /** * @dev Destroys a land, only land owner, or approved person/contract */ function destroy(uint256 _tokenId) public { require(isApprovedOrOwner(msg.sender, _tokenId)); _burn(msg.sender, _tokenId); } /** * @dev Gets all alnds in array * @return array of x, y, w, h */ function allLands(uint32 _checkWorld) public view returns (int64[], int64[]) { int64[] memory _xs = new int64[](allTokens.length); int64[] memory _ys = new int64[](allTokens.length); for (uint i = 0; i < allTokens.length; i++) { (uint32 _world, int64 _x, int64 _y) = decodeTokenId(allTokens[i]); if (_checkWorld != _world) continue; _xs[i] = _x; _ys[i] = _y; } return (_xs, _ys); } /** * @dev Resizes an existing land, only world owner or contract owner * Checking map overlap should be done in client side before */ function resize(uint32 _world, int64 _x, int64 _y, uint16 _w, uint16 _h) public onlyWorldOrContractOwner(_world) validPosition(_world, _x, _y) validSize(_w, _h) { uint256 tokenId = encodeTokenId(_world, _x, _y); widths_[tokenId] = _w; heights_[tokenId] = _h; } /** * @dev Returns an URI for a given position * Throws if the land at the position does not exist. May return an empty string. */ function tokenURI(uint32 _world, int64 _x, int64 _y) public view returns (string) { return tokenURI(encodeTokenId(_world, _x, _y)); } /** * @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) public view returns (string) { bytes memory uriByte = bytes(tokenURIs[_tokenId]); if (uriByte.length == 0) { (uint32 world, int64 x, int64 y) = decodeTokenId(_tokenId); return string(abi.encodePacked("http://api.block42.world/lands/", _uint32ToString(world), "/", _int2str(x), "/", _int2str(y))); } } function _uint32ToString(uint32 i) internal pure returns (string) { return _int2str(int(i)); } function _int2str(int i) internal pure returns (string){ if (i == 0) return "0"; bool negative = i < 0; uint j = uint(negative ? -i : i); uint l = j; // Keep an unsigned copy uint len; while (j != 0){ len++; j /= 10; } if (negative) ++len; // Make room for '-' sign bytes memory bstr = new bytes(len); uint k = len - 1; while (l != 0){ bstr[k--] = byte(48 + l % 10); l /= 10; } if (negative) { // Prepend '-' bstr[0] = '-'; } return string(bstr); } }
* @dev Resizes an existing land, only world owner or contract owner Checking map overlap should be done in client side before/
function resize(uint32 _world, int64 _x, int64 _y, uint16 _w, uint16 _h) public onlyWorldOrContractOwner(_world) validPosition(_world, _x, _y) validSize(_w, _h) { uint256 tokenId = encodeTokenId(_world, _x, _y); widths_[tokenId] = _w; heights_[tokenId] = _h; }
13,033,702
[ 1, 607, 3128, 392, 2062, 19193, 16, 1338, 9117, 3410, 578, 6835, 3410, 24471, 852, 7227, 1410, 506, 2731, 316, 1004, 4889, 1865, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7041, 12, 11890, 1578, 389, 18179, 16, 509, 1105, 389, 92, 16, 509, 1105, 389, 93, 16, 2254, 2313, 389, 91, 16, 2254, 2313, 389, 76, 13, 1071, 1338, 18071, 1162, 8924, 5541, 24899, 18179, 13, 923, 2555, 24899, 18179, 16, 389, 92, 16, 389, 93, 13, 923, 1225, 24899, 91, 16, 389, 76, 13, 288, 203, 565, 2254, 5034, 1147, 548, 273, 2017, 1345, 548, 24899, 18179, 16, 389, 92, 16, 389, 93, 1769, 203, 565, 15801, 67, 63, 2316, 548, 65, 273, 389, 91, 31, 203, 565, 24779, 67, 63, 2316, 548, 65, 273, 389, 76, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x80D3aa08da59bAD8162690db11A91C70A8F48D6E/sources/Graveyard.sol
no per-wallet limit
_maxRemintsPerWallet = 0;
2,938,374
[ 1, 2135, 1534, 17, 19177, 1800, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 1896, 1933, 28142, 2173, 16936, 273, 374, 31, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) 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. * * [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() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.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 ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable 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( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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 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 // OpenZeppelin Contracts v4.4.0 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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 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 // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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: UNLICENSED pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; /** * @title Controller component * @dev For easy access to any core components */ abstract contract Controller is Initializable, UUPSUpgradeable, AccessControlUpgradeable { bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); mapping(address => address) private _admins; // slither-disable-next-line uninitialized-state bool private _paused; // slither-disable-next-line uninitialized-state address public pauseGuardian; /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Controller: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Controller: not paused"); _; } modifier onlyAdmin() { require(hasRole(ROLE_ADMIN, msg.sender), "Controller: not admin"); _; } modifier onlyGuardian() { require(pauseGuardian == msg.sender, "Controller: caller does not have the guardian role"); _; } //When using minimal deploy, do not call initialize directly during deploy, because msg.sender is the proxyFactory address, and you need to call it manually function __Controller_init(address admin_) public initializer { require(admin_ != address(0), "Controller: address zero"); _paused = false; _admins[admin_] = admin_; __UUPSUpgradeable_init(); _setupRole(ROLE_ADMIN, admin_); pauseGuardian = admin_; } function _authorizeUpgrade(address) internal view override onlyAdmin {} /** * @dev Check if the address provided is the admin * @param account Account address */ function isAdmin(address account) public view returns (bool) { return hasRole(ROLE_ADMIN, account); } /** * @dev Add a new admin account * @param account Account address */ function addAdmin(address account) public onlyAdmin { require(account != address(0), "Controller: address zero"); require(_admins[account] == address(0), "Controller: admin already existed"); _admins[account] = account; _setupRole(ROLE_ADMIN, account); } /** * @dev Set pauseGuardian account * @param account Account address */ function setGuardian(address account) public onlyAdmin { pauseGuardian = account; } /** * @dev Renouce the admin from the sender's address */ function renounceAdmin() public { renounceRole(ROLE_ADMIN, msg.sender); delete _admins[msg.sender]; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyGuardian whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyGuardian whenPaused { _paused = false; emit Unpaused(msg.sender); } uint256[50] private ______gap; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title AssetManager Interface * @dev Manage the token balances staked by the users and deposited by admins, and invest tokens to the integrated underlying lending protocols. */ interface IAssetManager { /** * @dev Returns the balance of asset manager, plus the total amount of tokens deposited to all the underlying lending protocols. * @param tokenAddress ERC20 token address * @return Lending pool balance */ function getPoolBalance(address tokenAddress) external view returns (uint256); /** * @dev Returns the amount of the lending pool balance minus the amount of total staked. * @param tokenAddress ERC20 token address * @return Amount can be borrowed */ function getLoanableAmount(address tokenAddress) external view returns (uint256); /** * @dev Get the total amount of tokens deposited to all the integrated underlying protocols without side effects. * @param tokenAddress ERC20 token address * @return Total market balance */ function totalSupply(address tokenAddress) external returns (uint256); /** * @dev Get the total amount of tokens deposited to all the integrated underlying protocols, but without side effects. Safe to call anytime, but may not get the most updated number for the current block. Call totalSupply() for that purpose. * @param tokenAddress ERC20 token address * @return Total market balance */ function totalSupplyView(address tokenAddress) external view returns (uint256); /** * @dev Check if there is an underlying protocol available for the given ERC20 token. * @param tokenAddress ERC20 token address * @return Whether is supported */ function isMarketSupported(address tokenAddress) external view returns (bool); /** * @dev Deposit tokens to AssetManager, and those tokens will be passed along to adapters to deposit to integrated asset protocols if any is available. * @param token ERC20 token address * @param amount Deposit amount, in wei * @return Deposited amount */ function deposit(address token, uint256 amount) external returns (bool); /** * @dev Withdraw from AssetManager * @param token ERC20 token address * @param account User address * @param amount Withdraw amount, in wei * @return Withdraw amount */ function withdraw( address token, address account, uint256 amount ) external returns (bool); /** * @dev Add a new ERC20 token to support in AssetManager * @param tokenAddress ERC20 token address */ function addToken(address tokenAddress) external; /** * @dev Remove a ERC20 token to support in AssetManager * @param tokenAddress ERC20 token address */ function removeToken(address tokenAddress) external; /** * @dev Add a new adapter for the underlying lending protocol * @param adapterAddress adapter address */ function addAdapter(address adapterAddress) external; /** * @dev Remove a adapter for the underlying lending protocol * @param adapterAddress adapter address */ function removeAdapter(address adapterAddress) external; /** * @dev For a give token set allowance for all integrated money markets * @param tokenAddress ERC20 token address */ function approveAllMarketsMax(address tokenAddress) external; /** * @dev For a give moeny market set allowance for all underlying tokens * @param adapterAddress Address of adaptor for money market */ function approveAllTokensMax(address adapterAddress) external; /** * @dev Set withdraw sequence * @param newSeq priority sequence of money market indices to be used while withdrawing */ function changeWithdrawSequence(uint256[] calldata newSeq) external; /** * @dev Rebalance the tokens between integrated lending protocols * @param tokenAddress ERC20 token address * @param percentages Proportion */ function rebalance(address tokenAddress, uint256[] calldata percentages) external; /** * @dev Claim the tokens left on AssetManager balance, in case there are tokens get stuck here. * @param tokenAddress ERC20 token address * @param recipient Recipient address */ function claimTokens(address tokenAddress, address recipient) external; /** * @dev Claim the tokens stuck in the integrated adapters * @param index MoneyMarkets array index * @param tokenAddress ERC20 token address * @param recipient Recipient address */ function claimTokensFromAdapter( uint256 index, address tokenAddress, address recipient ) external; /** * @dev Get the number of supported underlying protocols. * @return MoneyMarkets length */ function moneyMarketsCount() external view returns (uint256); /** * @dev Get the count of supported tokens * @return Number of supported tokens */ function supportedTokensCount() external view returns (uint256); /** * @dev Get the supported lending protocol * @param tokenAddress ERC20 token address * @param marketId MoneyMarkets array index * @return tokenSupply */ function getMoneyMarket(address tokenAddress, uint256 marketId) external view returns (uint256, uint256); /** * @dev debt write off * @param tokenAddress ERC20 token address * @param amount WriteOff amount */ function debtWriteOff(address tokenAddress, uint256 amount) external; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title Comptroller Interface * @dev Work with UnionToken and UserManager to calculate the Union rewards based on the staking info from UserManager, and be ready to support multiple UserManagers for various tokens when we support multiple assets. */ interface IComptroller { /** * @dev Get the reward multipier based on the account status * @param account Account address * @return Multiplier number (in wei) */ function getRewardsMultiplier(address account, address token) external view returns (uint256); /** * @dev Withdraw rewards * @return Amount of rewards */ function withdrawRewards(address sender, address token) external returns (uint256); function addFrozenCoinAge( address staker, address token, uint256 lockedStake, uint256 lastRepay ) external; function updateTotalStaked(address token, uint256 totalStaked) external returns (bool); /** * @dev Calculate unclaimed rewards based on blocks * @param account User address * @param futureBlocks Number of blocks in the future * @return Unclaimed rewards */ function calculateRewardsByBlocks( address account, address token, uint256 futureBlocks ) external view returns (uint256); /** * @dev Calculate currently unclaimed rewards * @param account Account address * @return Unclaimed rewards */ function calculateRewards(address account, address token) external view returns (uint256); } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title CreditLimitModel Interface * @dev Calculate the user's credit line based on the trust he receives from the vouchees. */ interface ICreditLimitModel { struct LockedInfo { address staker; uint256 vouchingAmount; uint256 lockedAmount; uint256 availableStakingAmount; } function isCreditLimitModel() external pure returns (bool); function effectiveNumber() external returns (uint256); /** * @notice Calculates the staker locked amount * @return Member credit limit */ function getLockedAmount( LockedInfo[] calldata vouchAmountList, address staker, uint256 amount, bool isIncrease ) external pure returns (uint256); /** * @notice Calculates the member credit limit by vouchs * @return Member credit limit */ function getCreditLimit(uint256[] calldata vouchs) external view returns (uint256); } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; interface IDai { function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title UToken Interface * @dev Union members can borrow and repay thru this component. */ interface IUToken { /** * @dev Returns the remaining amount that can be borrowed from the market. * @return Remaining total amount */ function getRemainingDebtCeiling() external view returns (uint256); /** * @dev Get the borrowed principle * @param account Member address * @return Borrowed amount */ function getBorrowed(address account) external view returns (uint256); /** * @dev Get the last repay block * @param account Member address * @return Block number */ function getLastRepay(address account) external view returns (uint256); /** * @dev Get member interest index * @param account Member address * @return Interest index */ function getInterestIndex(address account) external view returns (uint256); /** * @dev Check if the member's loan is overdue * @param account Member address * @return Check result */ function checkIsOverdue(address account) external view returns (bool); /** * @dev Get the borrowing interest rate per block * @return Borrow rate */ function borrowRatePerBlock() external view returns (uint256); /** * @dev Get the origination fee * @param amount Amount to be calculated * @return Handling fee */ function calculatingFee(uint256 amount) external view returns (uint256); /** * @dev Calculating member's borrowed interest * @param account Member address * @return Interest amount */ function calculatingInterest(address account) external view returns (uint256); /** * @dev Get a member's current owed balance, including the principle and interest but without updating the user's states. * @param account Member address * @return Borrowed amount */ function borrowBalanceView(address account) external view returns (uint256); /** * @dev Change loan origination fee value * Accept claims only from the admin * @param originationFee_ Fees deducted for each loan transaction */ function setOriginationFee(uint256 originationFee_) external; /** * @dev Update the market debt ceiling to a fixed amount, for example, 1 billion DAI etc. * Accept claims only from the admin * @param debtCeiling_ The debt limit for the whole system */ function setDebtCeiling(uint256 debtCeiling_) external; /** * @dev Update the max loan size * Accept claims only from the admin * @param maxBorrow_ Max loan amount per user */ function setMaxBorrow(uint256 maxBorrow_) external; /** * @dev Update the minimum loan size * Accept claims only from the admin * @param minBorrow_ Minimum loan amount per user */ function setMinBorrow(uint256 minBorrow_) external; /** * @dev Change loan overdue duration, based on the number of blocks * Accept claims only from the admin * @param overdueBlocks_ Maximum late repayment block. The number of arrivals is a default */ function setOverdueBlocks(uint256 overdueBlocks_) external; /** * @dev Change to a different interest rate model * Accept claims only from the admin * @param newInterestRateModel New interest rate model address */ function setInterestRateModel(address newInterestRateModel) external; function setReserveFactor(uint256 reserveFactorMantissa_) external; function supplyRatePerBlock() external returns (uint256); function accrueInterest() external returns (bool); function balanceOfUnderlying(address owner) external returns (uint256); function mint(uint256 mintAmount) external; function redeem(uint256 redeemTokens) external; function redeemUnderlying(uint256 redeemAmount) external; function addReserves(uint256 addAmount) external; function removeReserves(address receiver, uint256 reduceAmount) external; /** * @dev Borrowing from the market * Accept claims only from the member * Borrow amount must in the range of creditLimit, minLoan, debtCeiling and not overdue * @param amount Borrow amount */ function borrow(uint256 amount) external; /** * @dev Repay the loan * Accept claims only from the member * Updated member lastPaymentEpoch only when the repayment amount is greater than interest * @param amount Repay amount */ function repayBorrow(uint256 amount) external; /** * @dev Repay the loan * Accept claims only from the member * Updated member lastPaymentEpoch only when the repayment amount is greater than interest * @param borrower Borrower address * @param amount Repay amount */ function repayBorrowBehalf(address borrower, uint256 amount) external; /** * @dev Update borrower overdue info * @param account Borrower address */ function updateOverdueInfo(address account) external; /** * @dev debt write off * @param borrower Borrower address * @param amount WriteOff amount */ function debtWriteOff(address borrower, uint256 amount) external; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title UnionToken Interface * @dev Mint and distribute UnionTokens. */ interface IUnionToken { /** * @dev Get total supply * @return Total supply */ function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function mint(address account, uint256 amount) external returns (bool); /** * @dev 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. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256); /** * @dev Allows to spend owner's Union tokens by the specified spender. * The function can be called by anyone, but requires having allowance parameters * signed by the owner according to EIP712. * @param owner The owner's address, cannot be zero address. * @param spender The spender's address, cannot be zero address. * @param value The allowance amount, in wei. * @param deadline The allowance expiration date (unix timestamp in UTC). * @param v A final byte of signature (ECDSA component). * @param r The first 32 bytes of signature (ECDSA component). * @param s The second 32 bytes of signature (ECDSA component). */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function burnFrom(address account, uint256 amount) external; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title UserManager Interface * @dev Manages the Union members credit lines, and their vouchees and borrowers info. */ interface IUserManager { /** * @dev Check if the account is a valid member * @param account Member address * @return Address whether is member */ function checkIsMember(address account) external view returns (bool); /** * @dev Get member borrowerAddresses * @param account Member address * @return Address array */ function getBorrowerAddresses(address account) external view returns (address[] memory); /** * @dev Get member stakerAddresses * @param account Member address * @return Address array */ function getStakerAddresses(address account) external view returns (address[] memory); /** * @dev Get member backer asset * @param account Member address * @param borrower Borrower address * @return Trust amount, vouch amount, and locked stake amount */ function getBorrowerAsset(address account, address borrower) external view returns ( uint256, uint256, uint256 ); /** * @dev Get member stakers asset * @param account Member address * @param staker Staker address * @return Vouch amount and lockedStake */ function getStakerAsset(address account, address staker) external view returns ( uint256, uint256, uint256 ); /** * @dev Get the member's available credit line * @param account Member address * @return Limit */ function getCreditLimit(address account) external view returns (int256); function totalStaked() external view returns (uint256); function totalFrozen() external view returns (uint256); function getFrozenCoinAge(address staker, uint256 pastBlocks) external view returns (uint256); /** * @dev Add a new member * Accept claims only from the admin * @param account Member address */ function addMember(address account) external; /** * @dev Update the trust amount for exisitng members. * @param borrower Borrower address * @param trustAmount Trust amount */ function updateTrust(address borrower, uint256 trustAmount) external; /** * @dev Apply for membership, and burn UnionToken as application fees * @param newMember New member address */ function registerMember(address newMember) external; /** * @dev Stop vouch for other member. * @param staker Staker address * @param account Account address */ function cancelVouch(address staker, address account) external; /** * @dev Change the credit limit model * Accept claims only from the admin * @param newCreditLimitModel New credit limit model address */ function setCreditLimitModel(address newCreditLimitModel) external; /** * @dev Get the user's locked stake from all his backed loans * @param staker Staker address * @return LockedStake */ function getTotalLockedStake(address staker) external view returns (uint256); /** * @dev Get staker's defaulted / frozen staked token amount * @param staker Staker address * @return Frozen token amount */ function getTotalFrozenAmount(address staker) external view returns (uint256); /** * @dev Update userManager locked info * @param borrower Borrower address * @param amount Borrow or repay amount(Including previously accrued interest) * @param isBorrow True is borrow, false is repay */ function updateLockedData( address borrower, uint256 amount, bool isBorrow ) external; /** * @dev Get the user's deposited stake amount * @param account Member address * @return Deposited stake amount */ function getStakerBalance(address account) external view returns (uint256); /** * @dev Stake * @param amount Amount */ function stake(uint256 amount) external; /** * @dev Unstake * @param amount Amount */ function unstake(uint256 amount) external; /** * @dev Update total frozen * @param account borrower address * @param isOverdue account is overdue */ function updateTotalFrozen(address account, bool isOverdue) external; function batchUpdateTotalFrozen(address[] calldata account, bool[] calldata isOverdue) external; /** * @dev Repay user's loan overdue, called only from the lending market * @param account User address * @param lastRepay Last repay block number */ function repayLoanOverdue( address account, address token, uint256 lastRepay ) external; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "../Controller.sol"; import "../interfaces/IAssetManager.sol"; import "../interfaces/ICreditLimitModel.sol"; import "../interfaces/IUserManager.sol"; import "../interfaces/IComptroller.sol"; import "../interfaces/IUnionToken.sol"; import "../interfaces/IDai.sol"; import "../interfaces/IUToken.sol"; /** * @title UserManager Contract * @dev Manages the Union members credit lines, and their vouchees and borrowers info. */ contract UserManager is Controller, IUserManager, ReentrancyGuardUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; struct Member { bool isMember; CreditLine creditLine; } //address: member address, uint256: trustAmount struct CreditLine { mapping(address => uint256) borrowers; address[] borrowerAddresses; mapping(address => uint256) stakers; address[] stakerAddresses; mapping(address => uint256) lockedAmount; } struct TrustInfo { address[] stakerAddresses; address[] borrowerAddresses; uint256 effectiveCount; address staker; uint256 vouchingAmount; uint256 stakingAmount; uint256 availableStakingAmount; uint256 lockedStake; uint256 totalLockedStake; } uint256 public constant MAX_TRUST_LIMIT = 100; uint256 public maxStakeAmount; address public stakingToken; address public unionToken; address public assetManager; IUToken public uToken; ICreditLimitModel public creditLimitModel; IComptroller public comptroller; uint256 public newMemberFee; // New member application fee // slither-disable-next-line constable-states uint256 public override totalStaked; // slither-disable-next-line constable-states uint256 public override totalFrozen; mapping(address => Member) private members; // slither-disable-next-line uninitialized-state mapping(address => uint256) public stakers; //1 user address 2 amount mapping(address => uint256) public memberFrozen; //1 user address 2 frozen amount error AddressZero(); error AmountZero(); error ErrorData(); error AuthFailed(); error NotCreditLimitModel(); error ErrorSelfVouching(); error MaxTrustLimitReached(); error TrustAmountTooLarge(); error LockedStakeNonZero(); error NoExistingMember(); error NotEnoughStakers(); error StakeLimitReached(); error AssetManagerDepositFailed(); error AssetManagerWithdrawFailed(); error InsufficientBalance(); error ExceedsTotalStaked(); error NotOverdue(); error ExceedsLocked(); error ExceedsTotalFrozen(); error LengthNotMatch(); error ErrorTotalStake(); modifier onlyMember(address account) { if (!checkIsMember(account)) revert AuthFailed(); _; } modifier onlyMarketOrAdmin() { if (address(uToken) != msg.sender && !isAdmin(msg.sender)) revert AuthFailed(); _; } /** * @dev Update new credit limit model event * @param newCreditLimitModel New credit limit model address */ event LogNewCreditLimitModel(address newCreditLimitModel); /** * @dev Add new member event * @param member New member address */ event LogAddMember(address member); /** * @dev Update vouch for existing member event * @param staker Trustee address * @param borrower The address gets vouched for * @param trustAmount Vouch amount */ event LogUpdateTrust(address indexed staker, address indexed borrower, uint256 trustAmount); /** * @dev New member application event * @param account New member's voucher address * @param borrower New member address */ event LogRegisterMember(address indexed account, address indexed borrower); /** * @dev Cancel vouching for other member event * @param account New member's voucher address * @param borrower The address gets vouched for */ event LogCancelVouch(address indexed account, address indexed borrower); /** * @dev Stake event * @param account The staker's address * @param amount The amount of tokens to stake */ event LogStake(address indexed account, uint256 amount); /** * @dev Unstake event * @param account The staker's address * @param amount The amount of tokens to unstake */ event LogUnstake(address indexed account, uint256 amount); /** * @dev DebtWriteOff event * @param staker The staker's address * @param borrower The borrower's address * @param amount The amount of write off */ event LogDebtWriteOff(address indexed staker, address indexed borrower, uint256 amount); /** * @dev set utoken address * @param uToken new uToken address */ event LogSetUToken(address uToken); /** * @dev set new member fee * @param oldMemberFee old member fee * @param newMemberFee new member fee */ event LogSetNewMemberFee(uint256 oldMemberFee, uint256 newMemberFee); event LogSetMaxStakeAmount(uint256 oldMaxStakeAmount, uint256 newMaxStakeAmount); function __UserManager_init( address assetManager_, address unionToken_, address stakingToken_, address creditLimitModel_, address comptroller_, address admin_ ) public initializer { Controller.__Controller_init(admin_); ReentrancyGuardUpgradeable.__ReentrancyGuard_init(); _setCreditLimitModel(creditLimitModel_); comptroller = IComptroller(comptroller_); assetManager = assetManager_; unionToken = unionToken_; stakingToken = stakingToken_; newMemberFee = 10**18; // Set the default membership fee maxStakeAmount = 5000e18; } function setMaxStakeAmount(uint256 maxStakeAmount_) public onlyAdmin { uint256 oldMaxStakeAmount = maxStakeAmount; maxStakeAmount = maxStakeAmount_; emit LogSetMaxStakeAmount(oldMaxStakeAmount, maxStakeAmount); } function setUToken(address uToken_) public onlyAdmin { if (uToken_ == address(0)) revert AddressZero(); uToken = IUToken(uToken_); emit LogSetUToken(uToken_); } function setNewMemberFee(uint256 amount) public onlyAdmin { uint256 oldMemberFee = newMemberFee; newMemberFee = amount; emit LogSetNewMemberFee(oldMemberFee, newMemberFee); } /** * @dev Change the credit limit model * Accept claims only from the admin * @param newCreditLimitModel New credit limit model address */ function setCreditLimitModel(address newCreditLimitModel) public override onlyAdmin { if (newCreditLimitModel == address(0)) revert AddressZero(); _setCreditLimitModel(newCreditLimitModel); } function _setCreditLimitModel(address newCreditLimitModel) private { if (!ICreditLimitModel(newCreditLimitModel).isCreditLimitModel()) revert NotCreditLimitModel(); creditLimitModel = ICreditLimitModel(newCreditLimitModel); emit LogNewCreditLimitModel(newCreditLimitModel); } /** * @dev Check if the account is a valid member * @param account Member address * @return Address whether is member */ function checkIsMember(address account) public view override returns (bool) { return members[account].isMember; } /** * @dev Get member borrowerAddresses * @param account Member address * @return Address array */ function getBorrowerAddresses(address account) public view override returns (address[] memory) { return members[account].creditLine.borrowerAddresses; } /** * @dev Get member stakerAddresses * @param account Member address * @return Address array */ function getStakerAddresses(address account) public view override returns (address[] memory) { return members[account].creditLine.stakerAddresses; } /** * @dev Get member backer asset * @param account Member address * @param borrower Borrower address * @return trustAmount vouchingAmount lockedStake. Trust amount, vouch amount, and locked stake amount */ function getBorrowerAsset(address account, address borrower) public view override returns ( uint256 trustAmount, uint256 vouchingAmount, uint256 lockedStake ) { trustAmount = members[account].creditLine.borrowers[borrower]; lockedStake = getLockedStake(account, borrower); vouchingAmount = getVouchingAmount(account, borrower); } /** * @dev Get member stakers asset * @param account Member address * @param staker Staker address * @return trustAmount lockedStake vouchingAmount. Vouch amount and lockedStake */ function getStakerAsset(address account, address staker) public view override returns ( uint256 trustAmount, uint256 vouchingAmount, uint256 lockedStake ) { trustAmount = members[account].creditLine.stakers[staker]; lockedStake = getLockedStake(staker, account); vouchingAmount = getVouchingAmount(staker, account); } /** * @dev Get staker locked stake for a borrower * @param staker Staker address * @param borrower Borrower address * @return LockedStake */ function getLockedStake(address staker, address borrower) public view returns (uint256) { return members[staker].creditLine.lockedAmount[borrower]; } /** * @dev Get the user's locked stake from all his backed loans * @param staker Staker address * @return LockedStake */ function getTotalLockedStake(address staker) public view override returns (uint256) { uint256 totalLockedStake = 0; uint256 stakingAmount = stakers[staker]; address[] memory borrowerAddresses = members[staker].creditLine.borrowerAddresses; address borrower; uint256 addressesLength = borrowerAddresses.length; for (uint256 i = 0; i < addressesLength; i++) { borrower = borrowerAddresses[i]; totalLockedStake += getLockedStake(staker, borrower); } if (stakingAmount >= totalLockedStake) { return totalLockedStake; } else { return stakingAmount; } } /** * @dev Get staker's defaulted / frozen staked token amount * @param staker Staker address * @return Frozen token amount */ function getTotalFrozenAmount(address staker) public view override returns (uint256) { TrustInfo memory trustInfo; uint256 totalFrozenAmount = 0; trustInfo.borrowerAddresses = members[staker].creditLine.borrowerAddresses; trustInfo.stakingAmount = stakers[staker]; address borrower; uint256 addressLength = trustInfo.borrowerAddresses.length; for (uint256 i = 0; i < addressLength; i++) { borrower = trustInfo.borrowerAddresses[i]; if (uToken.checkIsOverdue(borrower)) { totalFrozenAmount += getLockedStake(staker, borrower); } } if (trustInfo.stakingAmount >= totalFrozenAmount) { return totalFrozenAmount; } else { return trustInfo.stakingAmount; } } /** * @dev Get the member's available credit line * @param borrower Member address * @return Credit line amount */ function getCreditLimit(address borrower) public view override returns (int256) { TrustInfo memory trustInfo; trustInfo.stakerAddresses = members[borrower].creditLine.stakerAddresses; // Get the number of effective vouchee, first trustInfo.effectiveCount = 0; uint256 stakerAddressesLength = trustInfo.stakerAddresses.length; uint256[] memory limits = new uint256[](stakerAddressesLength); for (uint256 i = 0; i < stakerAddressesLength; i++) { trustInfo.staker = trustInfo.stakerAddresses[i]; trustInfo.stakingAmount = stakers[trustInfo.staker]; trustInfo.vouchingAmount = getVouchingAmount(trustInfo.staker, borrower); //A vouchingAmount value of 0 means that the amount of stake is 0 or trust is 0. In this case, this data is not used to calculate the credit limit if (trustInfo.vouchingAmount > 0) { //availableStakingAmount is staker‘s free stake amount trustInfo.borrowerAddresses = getBorrowerAddresses(trustInfo.staker); trustInfo.availableStakingAmount = trustInfo.stakingAmount; uint256 totalLockedStake = getTotalLockedStake(trustInfo.staker); if (trustInfo.stakingAmount <= totalLockedStake) { trustInfo.availableStakingAmount = 0; } else { trustInfo.availableStakingAmount = trustInfo.stakingAmount - totalLockedStake; } trustInfo.lockedStake = getLockedStake(trustInfo.staker, borrower); if (trustInfo.vouchingAmount < trustInfo.lockedStake) revert ErrorData(); //The actual effective guarantee amount cannot exceed availableStakingAmount, if (trustInfo.vouchingAmount >= trustInfo.availableStakingAmount + trustInfo.lockedStake) { limits[trustInfo.effectiveCount] = trustInfo.availableStakingAmount; } else { if (trustInfo.vouchingAmount <= trustInfo.lockedStake) { limits[trustInfo.effectiveCount] = 0; } else { limits[trustInfo.effectiveCount] = trustInfo.vouchingAmount - trustInfo.lockedStake; } } trustInfo.effectiveCount += 1; } } uint256[] memory creditlimits = new uint256[](trustInfo.effectiveCount); for (uint256 j = 0; j < trustInfo.effectiveCount; j++) { creditlimits[j] = limits[j]; } return int256(creditLimitModel.getCreditLimit(creditlimits)) - int256(uToken.calculatingInterest(borrower)); } /** * @dev Get vouching amount * @param staker Staker address * @param borrower Borrower address */ function getVouchingAmount(address staker, address borrower) public view returns (uint256) { uint256 totalStake = stakers[staker]; uint256 trustAmount = members[borrower].creditLine.stakers[staker]; return trustAmount > totalStake ? totalStake : trustAmount; } /** * @dev Get the user's deposited stake amount * @param account Member address * @return Deposited stake amount */ function getStakerBalance(address account) public view override returns (uint256) { return stakers[account]; } /** * @dev Add member * Accept claims only from the admin * @param account Member address */ function addMember(address account) public override onlyAdmin { members[account].isMember = true; emit LogAddMember(account); } /** * @dev Update the trust amount for exisitng members. * @param borrower_ Account address * @param trustAmount Trust amount */ function updateTrust(address borrower_, uint256 trustAmount) external override onlyMember(msg.sender) whenNotPaused { if (borrower_ == address(0)) revert AddressZero(); address borrower = borrower_; TrustInfo memory trustInfo; trustInfo.staker = msg.sender; if (trustInfo.staker == borrower) revert ErrorSelfVouching(); if ( members[borrower].creditLine.stakerAddresses.length >= MAX_TRUST_LIMIT || members[trustInfo.staker].creditLine.borrowerAddresses.length >= MAX_TRUST_LIMIT ) revert MaxTrustLimitReached(); trustInfo.borrowerAddresses = members[trustInfo.staker].creditLine.borrowerAddresses; trustInfo.stakerAddresses = members[borrower].creditLine.stakerAddresses; trustInfo.lockedStake = getLockedStake(trustInfo.staker, borrower); if (trustAmount < trustInfo.lockedStake) revert TrustAmountTooLarge(); uint256 borrowerCount = members[trustInfo.staker].creditLine.borrowerAddresses.length; bool borrowerExist = false; for (uint256 i = 0; i < borrowerCount; i++) { if (trustInfo.borrowerAddresses[i] == borrower) { borrowerExist = true; break; } } uint256 stakerCount = members[borrower].creditLine.stakerAddresses.length; bool stakerExist = false; for (uint256 i = 0; i < stakerCount; i++) { if (trustInfo.stakerAddresses[i] == trustInfo.staker) { stakerExist = true; break; } } if (!borrowerExist) { members[trustInfo.staker].creditLine.borrowerAddresses.push(borrower); } if (!stakerExist) { members[borrower].creditLine.stakerAddresses.push(trustInfo.staker); } members[trustInfo.staker].creditLine.borrowers[borrower] = trustAmount; members[borrower].creditLine.stakers[trustInfo.staker] = trustAmount; emit LogUpdateTrust(trustInfo.staker, borrower, trustAmount); } /** * @dev Stop vouch for other member. * @param staker Staker address * @param borrower borrower address */ function cancelVouch(address staker, address borrower) external override onlyMember(msg.sender) whenNotPaused { if (msg.sender != staker && msg.sender != borrower) revert AuthFailed(); if (getLockedStake(staker, borrower) != 0) revert LockedStakeNonZero(); uint256 stakerCount = members[borrower].creditLine.stakerAddresses.length; bool stakerExist = false; uint256 stakerIndex = 0; for (uint256 i = 0; i < stakerCount; i++) { if (members[borrower].creditLine.stakerAddresses[i] == staker) { stakerExist = true; stakerIndex = i; break; } } uint256 borrowerCount = members[staker].creditLine.borrowerAddresses.length; bool borrowerExist = false; uint256 borrowerIndex = 0; for (uint256 i = 0; i < borrowerCount; i++) { if (members[staker].creditLine.borrowerAddresses[i] == borrower) { borrowerExist = true; borrowerIndex = i; break; } } //delete address if (borrowerExist) { members[staker].creditLine.borrowerAddresses[borrowerIndex] = members[staker].creditLine.borrowerAddresses[ borrowerCount - 1 ]; members[staker].creditLine.borrowerAddresses.pop(); } if (stakerExist) { members[borrower].creditLine.stakerAddresses[stakerIndex] = members[borrower].creditLine.stakerAddresses[ stakerCount - 1 ]; members[borrower].creditLine.stakerAddresses.pop(); } delete members[staker].creditLine.borrowers[borrower]; delete members[borrower].creditLine.stakers[staker]; emit LogCancelVouch(staker, borrower); } function registerMemberWithPermit( address newMember, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public whenNotPaused { IUnionToken unionTokenContract = IUnionToken(unionToken); unionTokenContract.permit(msg.sender, address(this), value, deadline, v, r, s); registerMember(newMember); } /** * @dev Apply for membership, and burn UnionToken as application fees * @param newMember New member address */ function registerMember(address newMember) public override whenNotPaused { if (checkIsMember(newMember)) revert NoExistingMember(); IUnionToken unionTokenContract = IUnionToken(unionToken); uint256 effectiveStakerNumber = 0; address stakerAddress; uint256 addressesLength = members[newMember].creditLine.stakerAddresses.length; for (uint256 i = 0; i < addressesLength; i++) { stakerAddress = members[newMember].creditLine.stakerAddresses[i]; if (checkIsMember(stakerAddress) && getVouchingAmount(stakerAddress, newMember) > 0) effectiveStakerNumber += 1; } if (effectiveStakerNumber < creditLimitModel.effectiveNumber()) revert NotEnoughStakers(); members[newMember].isMember = true; unionTokenContract.burnFrom(msg.sender, newMemberFee); emit LogRegisterMember(msg.sender, newMember); } function updateLockedData( address borrower, uint256 amount, bool isBorrow ) external override onlyMarketOrAdmin { TrustInfo memory trustInfo; trustInfo.stakerAddresses = members[borrower].creditLine.stakerAddresses; ICreditLimitModel.LockedInfo[] memory lockedInfoList = new ICreditLimitModel.LockedInfo[]( trustInfo.stakerAddresses.length ); uint256 addressesLength = trustInfo.stakerAddresses.length; for (uint256 i = 0; i < addressesLength; i++) { ICreditLimitModel.LockedInfo memory lockedInfo; trustInfo.staker = trustInfo.stakerAddresses[i]; trustInfo.stakingAmount = stakers[trustInfo.staker]; trustInfo.vouchingAmount = getVouchingAmount(trustInfo.staker, borrower); trustInfo.totalLockedStake = getTotalLockedStake(trustInfo.staker); if (trustInfo.stakingAmount <= trustInfo.totalLockedStake) { trustInfo.availableStakingAmount = 0; } else { trustInfo.availableStakingAmount = trustInfo.stakingAmount - trustInfo.totalLockedStake; } lockedInfo.staker = trustInfo.staker; lockedInfo.vouchingAmount = trustInfo.vouchingAmount; lockedInfo.lockedAmount = getLockedStake(trustInfo.staker, borrower); lockedInfo.availableStakingAmount = trustInfo.availableStakingAmount; lockedInfoList[i] = lockedInfo; } uint256 lockedInfoListLength = lockedInfoList.length; for (uint256 i = 0; i < lockedInfoListLength; i++) { members[lockedInfoList[i].staker].creditLine.lockedAmount[borrower] = creditLimitModel.getLockedAmount( lockedInfoList, lockedInfoList[i].staker, amount, isBorrow ); } } /** * @dev Stake * @param amount Amount */ function stake(uint256 amount) public override whenNotPaused nonReentrant { IERC20Upgradeable erc20Token = IERC20Upgradeable(stakingToken); comptroller.withdrawRewards(msg.sender, stakingToken); uint256 balance = stakers[msg.sender]; if (balance + amount > maxStakeAmount) revert StakeLimitReached(); stakers[msg.sender] = balance + amount; totalStaked += amount; erc20Token.safeTransferFrom(msg.sender, address(this), amount); erc20Token.safeApprove(assetManager, 0); erc20Token.safeApprove(assetManager, amount); if (!IAssetManager(assetManager).deposit(stakingToken, amount)) revert AssetManagerDepositFailed(); emit LogStake(msg.sender, amount); } /** * @dev stakeWithPermit * @param amount Amount */ function stakeWithPermit( uint256 amount, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public whenNotPaused { IDai erc20Token = IDai(stakingToken); erc20Token.permit(msg.sender, address(this), nonce, expiry, true, v, r, s); stake(amount); } /** * @dev Unstake * @param amount Amount */ function unstake(uint256 amount) external override whenNotPaused nonReentrant { IERC20Upgradeable erc20Token = IERC20Upgradeable(stakingToken); uint256 stakingAmount = stakers[msg.sender]; if (stakingAmount - getTotalLockedStake(msg.sender) < amount) revert InsufficientBalance(); comptroller.withdrawRewards(msg.sender, stakingToken); stakers[msg.sender] = stakingAmount - amount; totalStaked -= amount; if (!IAssetManager(assetManager).withdraw(stakingToken, address(this), amount)) revert AssetManagerWithdrawFailed(); erc20Token.safeTransfer(msg.sender, amount); emit LogUnstake(msg.sender, amount); } function withdrawRewards() external whenNotPaused nonReentrant { comptroller.withdrawRewards(msg.sender, stakingToken); } /** * @dev Repay user's loan overdue, called only from the lending market * @param account User address * @param token The asset token repaying to * @param lastRepay Last repay block number */ function repayLoanOverdue( address account, address token, uint256 lastRepay ) external override whenNotPaused onlyMarketOrAdmin { address[] memory stakerAddresses = getStakerAddresses(account); uint256 addressesLength; for (uint256 i = 0; i < addressesLength; i++) { address staker = stakerAddresses[i]; (, , uint256 lockedStake) = getStakerAsset(account, staker); comptroller.addFrozenCoinAge(staker, token, lockedStake, lastRepay); } } //Only supports sumOfTrust function debtWriteOff(address borrower, uint256 amount) public { if (amount == 0) revert AmountZero(); if (amount > totalStaked) revert ExceedsTotalStaked(); if (!uToken.checkIsOverdue(borrower)) revert NotOverdue(); uint256 lockedAmount = getLockedStake(msg.sender, borrower); if (amount > lockedAmount) revert ExceedsLocked(); _updateTotalFrozen(borrower, true); if (amount > totalFrozen) revert ExceedsTotalFrozen(); comptroller.withdrawRewards(msg.sender, stakingToken); //The borrower is still overdue, do not call comptroller.addFrozenCoinAge stakers[msg.sender] -= amount; totalStaked -= amount; totalFrozen -= amount; if (memberFrozen[borrower] >= amount) { memberFrozen[borrower] -= amount; } else { memberFrozen[borrower] = 0; } members[msg.sender].creditLine.lockedAmount[borrower] = lockedAmount - amount; uint256 trustAmount = members[msg.sender].creditLine.borrowers[borrower]; uint256 newTrustAmount = trustAmount - amount; members[msg.sender].creditLine.borrowers[borrower] = newTrustAmount; members[borrower].creditLine.stakers[msg.sender] = newTrustAmount; IAssetManager(assetManager).debtWriteOff(stakingToken, amount); uToken.debtWriteOff(borrower, amount); emit LogDebtWriteOff(msg.sender, borrower, amount); } /** * @dev Update total frozen * @param account borrower address * @param isOverdue account is overdue */ function updateTotalFrozen(address account, bool isOverdue) external override onlyMarketOrAdmin whenNotPaused { if (totalStaked < totalFrozen) revert ErrorTotalStake(); uint256 effectiveTotalStaked = totalStaked - totalFrozen; comptroller.updateTotalStaked(stakingToken, effectiveTotalStaked); _updateTotalFrozen(account, isOverdue); } function batchUpdateTotalFrozen(address[] calldata accounts, bool[] calldata isOverdues) external override onlyMarketOrAdmin whenNotPaused { if (accounts.length != isOverdues.length) revert LengthNotMatch(); if (totalStaked < totalFrozen) revert ErrorTotalStake(); uint256 effectiveTotalStaked = totalStaked - totalFrozen; comptroller.updateTotalStaked(stakingToken, effectiveTotalStaked); for (uint256 i = 0; i < accounts.length; i++) { if (accounts[i] != address(0)) _updateTotalFrozen(accounts[i], isOverdues[i]); } } function _updateTotalFrozen(address account, bool isOverdue) private { if (isOverdue) { //isOverdue = true, user overdue needs to increase totalFrozen //The sum of the locked amount of all stakers on this borrower, which is the frozen amount that needs to be updated uint256 amount; for (uint256 i = 0; i < members[account].creditLine.stakerAddresses.length; i++) { address staker = members[account].creditLine.stakerAddresses[i]; uint256 lockedStake = getLockedStake(staker, account); amount += lockedStake; } if (memberFrozen[account] == 0) { //I haven’t updated the frozen amount about this borrower before, just increase the amount directly totalFrozen += amount; } else { //I have updated the frozen amount of this borrower before. After increasing the amount, subtract the previously increased value to avoid repeated additions. totalFrozen = totalFrozen + amount - memberFrozen[account]; } //Record the increased value of this borrower this time memberFrozen[account] = amount; } else { //isOverdue = false, the user loan needs to reduce the number of frozen last time to return to normal if (totalFrozen > memberFrozen[account]) { //Minus the frozen amount added last time totalFrozen -= memberFrozen[account]; } else { totalFrozen = 0; } memberFrozen[account] = 0; } } function getFrozenCoinAge(address staker, uint256 pastBlocks) public view override returns (uint256) { uint256 totalFrozenCoinAge = 0; address[] memory borrowerAddresses = getBorrowerAddresses(staker); uint256 addressLength = borrowerAddresses.length; for (uint256 i = 0; i < addressLength; i++) { address borrower = borrowerAddresses[i]; uint256 blocks = block.number - uToken.getLastRepay(borrower); if (uToken.checkIsOverdue(borrower)) { (, , uint256 lockedStake) = getStakerAsset(borrower, staker); if (pastBlocks >= blocks) { totalFrozenCoinAge = totalFrozenCoinAge + (lockedStake * blocks); } else { totalFrozenCoinAge = totalFrozenCoinAge + (lockedStake * pastBlocks); } } } return totalFrozenCoinAge; } }
* @dev Returns the remaining amount that can be borrowed from the market. @return Remaining total amount/* @dev Get the borrowed principle @param account Member address @return Borrowed amount/* @dev Get the last repay block @param account Member address @return Block number/* @dev Get member interest index @param account Member address @return Interest index/* @dev Check if the member's loan is overdue @param account Member address @return Check result/* @dev Get the borrowing interest rate per block @return Borrow rate/* @dev Get the origination fee @param amount Amount to be calculated @return Handling fee/* @dev Calculating member's borrowed interest @param account Member address @return Interest amount/* @dev Get a member's current owed balance, including the principle and interest but without updating the user's states. @param account Member address @return Borrowed amount/* @dev Change loan origination fee value Accept claims only from the admin @param originationFee_ Fees deducted for each loan transaction/* @dev Update the market debt ceiling to a fixed amount, for example, 1 billion DAI etc. Accept claims only from the admin @param debtCeiling_ The debt limit for the whole system/* @dev Update the max loan size Accept claims only from the admin @param maxBorrow_ Max loan amount per user/* @dev Update the minimum loan size Accept claims only from the admin @param minBorrow_ Minimum loan amount per user/* @dev Change loan overdue duration, based on the number of blocks Accept claims only from the admin @param overdueBlocks_ Maximum late repayment block. The number of arrivals is a default/* @dev Change to a different interest rate model Accept claims only from the admin @param newInterestRateModel New interest rate model address/* @dev Borrowing from the market Accept claims only from the member Borrow amount must in the range of creditLimit, minLoan, debtCeiling and not overdue @param amount Borrow amount/* @dev Repay the loan Accept claims only from the member Updated member lastPaymentEpoch only when the repayment amount is greater than interest @param amount Repay amount/* @dev Repay the loan Accept claims only from the member Updated member lastPaymentEpoch only when the repayment amount is greater than interest @param borrower Borrower address @param amount Repay amount/* @dev Update borrower overdue info @param account Borrower address/* @dev debt write off @param borrower Borrower address @param amount WriteOff amount/SPDX-License-Identifier: UNLICENSED* @title UnionToken Interface @dev Mint and distribute UnionTokens./
interface IUnionToken { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function mint(address account, uint256 amount) external returns (bool); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function burnFrom(address account, uint256 amount) external; }
528,770
[ 1, 1356, 326, 4463, 3844, 716, 848, 506, 29759, 329, 628, 326, 13667, 18, 225, 327, 2663, 3280, 2078, 3844, 19, 282, 968, 326, 29759, 329, 846, 9523, 2444, 282, 2236, 8596, 1758, 225, 327, 605, 15318, 329, 3844, 19, 282, 968, 326, 1142, 2071, 528, 1203, 282, 2236, 8596, 1758, 225, 327, 3914, 1300, 19, 282, 968, 3140, 16513, 770, 282, 2236, 8596, 1758, 225, 327, 5294, 395, 770, 19, 282, 2073, 309, 326, 3140, 1807, 28183, 353, 1879, 24334, 282, 2236, 8596, 1758, 225, 327, 2073, 563, 19, 282, 968, 326, 29759, 310, 16513, 4993, 1534, 1203, 225, 327, 605, 15318, 4993, 19, 282, 968, 326, 1647, 1735, 14036, 282, 3844, 16811, 358, 506, 8894, 225, 327, 2841, 2456, 14036, 19, 282, 15994, 1776, 3140, 1807, 29759, 329, 16513, 282, 2236, 8596, 1758, 225, 327, 5294, 395, 3844, 19, 282, 968, 279, 3140, 1807, 783, 2523, 329, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 5831, 467, 14325, 1345, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 312, 474, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 1689, 2432, 29637, 12, 2867, 2236, 16, 2254, 5034, 1203, 1854, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 21447, 12, 203, 3639, 1758, 3410, 16, 203, 3639, 1758, 17571, 264, 16, 203, 3639, 2254, 5034, 460, 16, 203, 3639, 2254, 5034, 14096, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 1731, 1578, 436, 16, 203, 3639, 1731, 1578, 272, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 18305, 1265, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 3903, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * Example script for the Ethereum development walkthrough */ contract Wrestling { /** * Our wrestlers */ address public wrestler1; address public wrestler2; bool public wrestler1Played; bool public wrestler2Played; uint private wrestler1Deposit; uint private wrestler2Deposit; bool public gameFinished; address public theWinner; uint gains; /** * The logs that will be emitted in every step of the contract's life cycle */ event WrestlingStartsEvent(address wrestler1, address wrestler2); event EndOfRoundEvent(uint wrestler1Deposit, uint wrestler2Deposit); event EndOfWrestlingEvent(address winner, uint gains); /** * The contract constructor */ function Wrestling() public { wrestler1 = msg.sender; } /** * A second wrestler can register as an opponent */ function registerAsAnOpponent() public { require(wrestler2 == address(0)); wrestler2 = msg.sender; WrestlingStartsEvent(wrestler1, wrestler2); } /** * Every round a player can put a sum of ether, if one of the player put in twice or * more the money (in total) than the other did, the first wins */ function wrestle() public payable { require(!gameFinished && (msg.sender == wrestler1 || msg.sender == wrestler2)); if (msg.sender == wrestler1) { require(wrestler1Played == false); wrestler1Played = true; wrestler1Deposit = wrestler1Deposit + msg.value; } else { require(wrestler2Played == false); wrestler2Played = true; wrestler2Deposit = wrestler2Deposit + msg.value; } if (wrestler1Played && wrestler2Played) { if (wrestler1Deposit >= wrestler2Deposit * 2) { endOfGame(wrestler1); } else if (wrestler2Deposit >= wrestler1Deposit * 2) { endOfGame(wrestler2); } else { endOfRound(); } } } function endOfRound() internal { wrestler1Played = false; wrestler2Played = false; EndOfRoundEvent(wrestler1Deposit, wrestler2Deposit); } function endOfGame(address winner) internal { gameFinished = true; theWinner = winner; gains = wrestler1Deposit + wrestler2Deposit; EndOfWrestlingEvent(winner, gains); } /** * The withdraw function, following the withdraw pattern shown and explained here: * http://solidity.readthedocs.io/en/develop/common-patterns.html#withdrawal-from-contracts */ function withdraw() public { require(gameFinished && theWinner == msg.sender); uint amount = gains; gains = 0; msg.sender.transfer(amount); } }
* Every round a player can put a sum of ether, if one of the player put in twice or more the money (in total) than the other did, the first wins/
function wrestle() public payable { require(!gameFinished && (msg.sender == wrestler1 || msg.sender == wrestler2)); if (msg.sender == wrestler1) { require(wrestler1Played == false); wrestler1Played = true; wrestler1Deposit = wrestler1Deposit + msg.value; require(wrestler2Played == false); wrestler2Played = true; wrestler2Deposit = wrestler2Deposit + msg.value; } if (wrestler1Played && wrestler2Played) { if (wrestler1Deposit >= wrestler2Deposit * 2) { endOfGame(wrestler1); endOfGame(wrestler2); endOfRound(); } } }
12,699,475
[ 1, 21465, 3643, 279, 7291, 848, 1378, 279, 2142, 434, 225, 2437, 16, 309, 1245, 434, 326, 7291, 1378, 316, 13605, 578, 1898, 326, 15601, 261, 267, 2078, 13, 2353, 326, 1308, 5061, 16, 326, 1122, 31307, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 341, 8792, 298, 1435, 1071, 8843, 429, 288, 203, 377, 202, 6528, 12, 5, 13957, 10577, 597, 261, 3576, 18, 15330, 422, 341, 8792, 749, 21, 747, 1234, 18, 15330, 422, 341, 8792, 749, 22, 10019, 203, 203, 377, 202, 430, 261, 3576, 18, 15330, 422, 341, 8792, 749, 21, 13, 288, 203, 377, 202, 202, 6528, 12, 91, 8792, 749, 21, 11765, 329, 422, 629, 1769, 203, 377, 202, 202, 91, 8792, 749, 21, 11765, 329, 273, 638, 31, 203, 377, 202, 202, 91, 8792, 749, 21, 758, 1724, 273, 341, 8792, 749, 21, 758, 1724, 397, 1234, 18, 1132, 31, 203, 377, 202, 202, 6528, 12, 91, 8792, 749, 22, 11765, 329, 422, 629, 1769, 203, 377, 202, 202, 91, 8792, 749, 22, 11765, 329, 273, 638, 31, 203, 377, 202, 202, 91, 8792, 749, 22, 758, 1724, 273, 341, 8792, 749, 22, 758, 1724, 397, 1234, 18, 1132, 31, 203, 377, 202, 97, 203, 203, 377, 202, 430, 261, 91, 8792, 749, 21, 11765, 329, 597, 341, 8792, 749, 22, 11765, 329, 13, 288, 203, 377, 202, 202, 430, 261, 91, 8792, 749, 21, 758, 1724, 1545, 341, 8792, 749, 22, 758, 1724, 380, 576, 13, 288, 203, 377, 1082, 202, 409, 951, 12496, 12, 91, 8792, 749, 21, 1769, 203, 377, 1082, 202, 409, 951, 12496, 12, 91, 8792, 749, 22, 1769, 203, 7734, 20706, 11066, 5621, 203, 377, 202, 202, 97, 203, 377, 202, 97, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100 ]
automat sg { tag eng_noun:term { HAS_APPOSITIVE_SLOT:1 } tag eng_noun:word { HAS_APPOSITIVE_SLOT:1 } tag eng_noun:hotel { HAS_APPOSITIVE_SLOT:1 } tag eng_noun:class { HAS_APPOSITIVE_SLOT:1 } // It is of class gM0. tag eng_noun:number { HAS_APPOSITIVE_SLOT:1 } // Morris was at number eleven. tag eng_noun:urge{ ENG_MODAL_NOUN } tag eng_noun:ability{ ENG_MODAL_NOUN } tag eng_noun:way{ ENG_MODAL_NOUN } // Excogitate a way to measure the speed of light. tag eng_noun:readiness{ ENG_MODAL_NOUN } // He showed a readiness to please. tag eng_noun:reluctance{ ENG_MODAL_NOUN } // He showed a reluctance to please. tag eng_noun:willingness{ ENG_MODAL_NOUN } // He showed a willingness to please. tag eng_noun:inclination{ ENG_MODAL_NOUN } // He showed an inclination to please. tag eng_noun:determination{ ENG_MODAL_NOUN } // He showed a determination to please. tag eng_noun:aptness{ ENG_MODAL_NOUN } // The aptness of iron to rust tag eng_noun:attempt{ ENG_MODAL_NOUN } // Feckless attempts to repair the plumbing. tag eng_noun:Loath{ ENG_MODAL_NOUN } // Loath to admit a mistake. tag eng_noun:effort{ ENG_MODAL_NOUN } // She sneered at her little sister's efforts to play the song on the piano. tag eng_noun:pleasure{ ENG_MODAL_NOUN } tag eng_noun:chance{ ENG_MODAL_NOUN } // She never misses a chance to grandstand. tag eng_noun:anxiety{ ENG_MODAL_NOUN } // He showed an anxiety to please. tag eng_noun:failure{ ENG_MODAL_NOUN } // failure to define one testable variable }
She never misses a chance to grandstand.
tag eng_noun:chance{ ENG_MODAL_NOUN }
12,664,870
[ 1, 55, 580, 5903, 12543, 281, 279, 17920, 358, 16225, 10145, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1047, 24691, 67, 82, 465, 30, 343, 1359, 95, 17979, 67, 6720, 1013, 67, 3417, 2124, 289, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; // Goals of Staking V2 // 1. Stake RandomWalkNFT, Spiral, Crystals, SPIRALBITS and IMPISH // 2. Allow Crystals to grow - both size and target symmetry // 3. Allow Spirals to claim win if Spiral game ends // 4. Allow listing on marketplace while staked // A note on how TokenIDs work. // TokenIDs stored inside the contract have to be >1M // 1M+ -> RandomWalkNFT // 2M+ -> Spiral // 3M+ -> Staked Crystal that is growing // 4M+ -> Fully grown crystal that is earning SPIRALBITS import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./ImpishCrystal.sol"; import "./ImpishSpiral.sol"; import "./SpiralBits.sol"; // import "hardhat/console.sol"; abstract contract IRPS { function commit( bytes32 commitment, address player, uint32[] calldata crystalIDs ) external virtual; } contract StakingV2 is IERC721ReceiverUpgradeable, ReentrancyGuardUpgradeable, OwnableUpgradeable { // Since this is an upgradable implementation, the storage layout is important. // Please be careful changing variable positions when upgrading. // Global reward for all SPIRALBITS staked per second, across ALL staked SpiralBits uint256 public SPIRALBITS_STAKING_EMISSION_PER_SEC; // Global reward for all IMPISH staked per second, across ALL staked IMPISH uint256 public IMPISH_STAKING_EMISSION_PER_SEC; // How many SpiralBits per second are awarded to a staked spiral // 0.167 SPIRALBITS per second. (10 SPIRALBITS per 60 seconds) uint256 public SPIRALBITS_PER_SECOND_PER_SPIRAL; // How many SpiralBits per second are awarded to a staked RandomWalkNFTs // 0.0167 SPIRALBITS per second. (1 SPIRALBITS per 60 seconds) uint256 public SPIRALBITS_PER_SECOND_PER_RW; // How many SpiralBits per second are awarded to a staked, fully grown // spiral. 0.0835 SPIRALBITS per second (5 SPIRALBITS per 60 seconds) uint256 public SPIRALBITS_PER_SECOND_PER_CRYSTAL; // We're staking this NFT in this contract IERC721 public randomWalkNFT; ImpishSpiral public impishspiral; ImpishCrystal public crystals; // The token that is being issued for staking SpiralBits public spiralbits; // The Impish Token IERC20 public impish; struct RewardEpoch { uint32 epochDurationSec; // Total seconds that this epoch lasted uint96 totalSpiralBitsStaked; // Total SPIRALBITS staked across all accounts in whole uints for this Epoch uint96 totalImpishStaked; // Total IMPISH tokens staked across all accounts in whole units for this Epoch } RewardEpoch[] public epochs; // List of epochs uint32 public lastEpochTime; // Last epoch ended at this time struct StakedNFTAndTokens { uint16 numRWStaked; uint16 numSpiralsStaked; uint16 numGrowingCrystalsStaked; uint16 numFullCrystalsStaked; uint32 lastClaimEpoch; // Last Epoch number the rewards were accumulated into claimedSpiralBits. Cannot be 0. uint96 spiralBitsStaked; // Total number of SPIRALBITS staked uint96 impishStaked; // Total number of IMPISH tokens staked uint96 claimedSpiralBits; // Already claimed (but not withdrawn) spiralBits before lastClaimTime mapping(uint256 => uint256) ownedTokens; // index => tokenId } struct TokenIdInfo { uint256 ownedTokensIndex; address owner; } // Mapping of Contract TokenID => Address that staked it. mapping(uint256 => TokenIdInfo) public stakedTokenOwners; // Address that staked the token => Token Accounting mapping(address => StakedNFTAndTokens) public stakedNFTsAndTokens; mapping(uint32 => uint8) public crystalTargetSyms; // V2 fields // They have to be at the end, because we don't want to overwrite the storage address public rps; // Upgradable contracts use initialize instead of constructors function initialize(address _crystals) public initializer { // Call super initializers __Ownable_init(); __ReentrancyGuard_init(); SPIRALBITS_STAKING_EMISSION_PER_SEC = 4 ether; IMPISH_STAKING_EMISSION_PER_SEC = 1 ether; SPIRALBITS_PER_SECOND_PER_SPIRAL = 0.167 ether * 1.1; // 10% bonus SPIRALBITS_PER_SECOND_PER_RW = 0.0167 ether * 1.8; // 80% bonus SPIRALBITS_PER_SECOND_PER_CRYSTAL = 0.0835 ether; crystals = ImpishCrystal(_crystals); impishspiral = ImpishSpiral(crystals.spirals()); randomWalkNFT = IERC721(impishspiral._rwNFT()); spiralbits = SpiralBits(crystals.SpiralBits()); impish = IERC20(impishspiral._impishDAO()); // To make accounting easier, we put a dummy epoch here epochs.push(RewardEpoch({epochDurationSec: 0, totalSpiralBitsStaked: 0, totalImpishStaked: 0})); // Authorize spiralbits to be spent from this contact by the Crystals contracts, used to grow crystals spiralbits.approve(_crystals, 2_000_000_000 ether); lastEpochTime = uint32(block.timestamp); } function stakeSpiralBits(uint256 amount) external { stakeSpiralBitsForOwner(amount, msg.sender); } function stakeSpiralBitsForOwner(uint256 amount, address owner) public nonReentrant { require(amount > 0, "Need SPIRALBITS"); // Update the owner's rewards. The newly added epoch doesn't matter, because it's duration is 0. // This has to be done before _updateRewards(owner); // Transfer the SpiralBits in. If amount is bad or user doesn't have enough tokens, this will fail. spiralbits.transferFrom(msg.sender, address(this), amount); // Spiralbits accounting stakedNFTsAndTokens[owner].spiralBitsStaked += uint96(amount); } function unstakeSpiralBits(bool claimReward) external nonReentrant { uint256 amount = stakedNFTsAndTokens[msg.sender].spiralBitsStaked; require(amount > 0, "NoSPIRALBITSToUnstake"); // Update the owner's rewards first. This also updates the current epoch, since nothing has changed yet. _updateRewards(msg.sender); // Impish accounting stakedNFTsAndTokens[msg.sender].spiralBitsStaked = 0; // Transfer Spiralbits out. spiralbits.transfer(msg.sender, amount); if (claimReward) { _claimRewards(msg.sender); } } function stakeImpish(uint256 amount) external { stakeImpishForOwner(amount, msg.sender); } function stakeImpishForOwner(uint256 amount, address owner) public nonReentrant { require(amount > 0, "Need IMPISH"); // Update the owner's rewards first. This also updates the current epoch, since nothing has changed yet. _updateRewards(owner); // Transfer the SpiralBits in. If amount is bad or user doesn't have enoug htokens, this will fail. impish.transferFrom(msg.sender, address(this), amount); // Impish accounting stakedNFTsAndTokens[owner].impishStaked += uint96(amount); } function unstakeImpish(bool claimReward) external nonReentrant { uint256 amount = stakedNFTsAndTokens[msg.sender].impishStaked; require(amount > 0, "No IMPISH to Unstake"); // Update the owner's rewards first. This also updates the current epoch, since nothing has changed yet. _updateRewards(msg.sender); // Impish accounting stakedNFTsAndTokens[msg.sender].impishStaked = 0; // Transfer impish out. impish.transfer(msg.sender, amount); if (claimReward) { _claimRewards(msg.sender); } } function stakeNFTsForOwner(uint32[] calldata contractTokenIds, address owner) external nonReentrant { // Update the owner's rewards first. This also updates the current epoch, since nothing has changed yet. _updateRewards(owner); for (uint256 i = 0; i < contractTokenIds.length; i++) { require(contractTokenIds[i] > 1_000_000, "UseContractTokenIDs"); uint32 nftType = contractTokenIds[i] / 1_000_000; uint32 tokenId = contractTokenIds[i] % 1_000_000; if (nftType == 1) { _stakeNFT(randomWalkNFT, owner, uint256(tokenId), 1_000_000); // Add this RWNFT to the staked struct stakedNFTsAndTokens[owner].numRWStaked += 1; } else if (nftType == 2) { _stakeNFT(impishspiral, owner, uint256(tokenId), 2_000_000); // Add this spiral to the staked struct stakedNFTsAndTokens[owner].numSpiralsStaked += 1; } else if (nftType == 3) { // Crystals that are growing _stakeNFT(crystals, owner, uint256(tokenId), 3_000_000); // Add this crystal (Growing) to the staked struct stakedNFTsAndTokens[owner].numGrowingCrystalsStaked += 1; } else if (nftType == 4) { // Crystals that are fully grown (uint8 currentCrystalSize, , , , ) = crystals.crystals(tokenId); require(currentCrystalSize == 100, "CrystalNotFullyGrown"); _stakeNFT(crystals, owner, uint256(tokenId), 4_000_000); // Add this crystal (fully grown) to the staked struct stakedNFTsAndTokens[owner].numFullCrystalsStaked += 1; } else { revert("InvalidNFTType"); } } } function unstakeNFTs(uint32[] calldata contractTokenIds, bool claim) external nonReentrant { // Update the owner's rewards first. This also updates the current epoch. _updateRewards(msg.sender); for (uint256 i = 0; i < contractTokenIds.length; i++) { require(contractTokenIds[i] > 1_000_000, "UseContractTokenIDs"); uint32 nftType = contractTokenIds[i] / 1_000_000; uint32 tokenId = contractTokenIds[i] % 1_000_000; if (nftType == 1) { _unstakeNFT(randomWalkNFT, uint256(tokenId), 1_000_000); // Add this RWNFT to the staked struct stakedNFTsAndTokens[msg.sender].numRWStaked -= 1; } else if (nftType == 2) { _unstakeNFT(impishspiral, uint256(tokenId), 2_000_000); // Add this spiral to the staked struct stakedNFTsAndTokens[msg.sender].numSpiralsStaked -= 1; } else if (nftType == 3) { // Crystals that are growing _unstakeNFT(crystals, uint256(tokenId), 3_000_000); // Add this crystal (Growing) to the staked struct stakedNFTsAndTokens[msg.sender].numGrowingCrystalsStaked -= 1; delete crystalTargetSyms[tokenId + 3_000_000]; } else if (nftType == 4) { // Crystals that are growing _unstakeNFT(crystals, uint256(tokenId), 4_000_000); // Add this crystal (fully grown) to the staked struct stakedNFTsAndTokens[msg.sender].numFullCrystalsStaked -= 1; } else { revert("InvalidNFTType"); } } if (claim) { _claimRewards(msg.sender); } } function pendingRewards(address owner) public view returns (uint256) { uint256 lastClaimedEpoch = stakedNFTsAndTokens[owner].lastClaimEpoch; // Start with already claimed epochs uint256 accumulated = stakedNFTsAndTokens[owner].claimedSpiralBits; // Add up all pending epochs if (lastClaimedEpoch > 0) { accumulated += _getRewardsAccumulated(owner, lastClaimedEpoch); } // Add potentially upcoming epoch RewardEpoch memory newEpoch = _getNextEpoch(); if (newEpoch.epochDurationSec > 0) { // Accumulate what will probably be the next epoch if (newEpoch.totalSpiralBitsStaked > 0) { accumulated += (SPIRALBITS_STAKING_EMISSION_PER_SEC * newEpoch.epochDurationSec * uint256(stakedNFTsAndTokens[owner].spiralBitsStaked)) / uint256(newEpoch.totalSpiralBitsStaked); } if (newEpoch.totalImpishStaked > 0) { accumulated += (IMPISH_STAKING_EMISSION_PER_SEC * newEpoch.epochDurationSec * uint256(stakedNFTsAndTokens[owner].impishStaked)) / uint256(newEpoch.totalImpishStaked); } // Rewards for Staked Spirals accumulated += newEpoch.epochDurationSec * SPIRALBITS_PER_SECOND_PER_SPIRAL * stakedNFTsAndTokens[owner].numSpiralsStaked; // Rewards for staked RandomWalks accumulated += newEpoch.epochDurationSec * SPIRALBITS_PER_SECOND_PER_RW * stakedNFTsAndTokens[owner].numRWStaked; // Rewards for staked fully grown crystals accumulated += newEpoch.epochDurationSec * SPIRALBITS_PER_SECOND_PER_CRYSTAL * stakedNFTsAndTokens[owner].numFullCrystalsStaked; } // Note: Growing crystals do not accumulate rewards return accumulated; } // --------------------- // Internal Functions // --------------------- // Claim the pending rewards function _claimRewards(address owner) internal { _updateRewards(owner); uint256 rewardsPending = stakedNFTsAndTokens[owner].claimedSpiralBits; // If there are any rewards, if (rewardsPending > 0) { // Mark rewards as claimed stakedNFTsAndTokens[owner].claimedSpiralBits = 0; // Mint new spiralbits directly to the claimer spiralbits.mintSpiralBits(owner, rewardsPending); } } // Stake an NFT function _stakeNFT( IERC721 nft, address owner, uint256 tokenId, uint256 tokenIdMultiplier ) internal { require(nft.ownerOf(tokenId) == msg.sender, "DontOwnNFT"); uint256 contractTokenId = tokenIdMultiplier + tokenId; // Add the spiral to staked owner list to keep track of staked tokens _addTokenToOwnerEnumeration(owner, contractTokenId); stakedTokenOwners[contractTokenId].owner = owner; // Transfer the actual NFT to this staking contract. nft.safeTransferFrom(msg.sender, address(this), tokenId); } // Unstake an NFT and return it back to the sender function _unstakeNFT( IERC721 nft, uint256 tokenId, uint256 tokenIdMultiplier ) internal { uint256 contractTokenId = tokenIdMultiplier + tokenId; require(stakedTokenOwners[contractTokenId].owner == msg.sender, "DontOwnNFT"); _removeTokenFromOwnerEnumeration(msg.sender, contractTokenId); // Transfer the NFT out nft.safeTransferFrom(address(this), msg.sender, tokenId); } function _getRewardsAccumulated(address owner, uint256 lastClaimedEpoch) internal view returns (uint256) { uint256 rewardsAccumulated = 0; uint256 totalDuration = 0; for (uint256 i = lastClaimedEpoch + 1; i < epochs.length; i++) { // Accumulate the durations, so we can add the NFT rewards too totalDuration += epochs[i].epochDurationSec; // Accumulate spiralbits reward if (epochs[i].totalSpiralBitsStaked > 0) { rewardsAccumulated += (SPIRALBITS_STAKING_EMISSION_PER_SEC * uint256(epochs[i].epochDurationSec) * uint256(stakedNFTsAndTokens[owner].spiralBitsStaked)) / uint256(epochs[i].totalSpiralBitsStaked); } // accumulate impish rewards if (epochs[i].totalImpishStaked > 0) { rewardsAccumulated += (IMPISH_STAKING_EMISSION_PER_SEC * uint256(epochs[i].epochDurationSec) * uint256(stakedNFTsAndTokens[owner].impishStaked)) / uint256(epochs[i].totalImpishStaked); } } // Rewards for Staked Spirals rewardsAccumulated += totalDuration * SPIRALBITS_PER_SECOND_PER_SPIRAL * stakedNFTsAndTokens[owner].numSpiralsStaked; // Rewards for staked RandomWalks rewardsAccumulated += totalDuration * SPIRALBITS_PER_SECOND_PER_RW * stakedNFTsAndTokens[owner].numRWStaked; // Rewards for staked fully grown crystals rewardsAccumulated += totalDuration * SPIRALBITS_PER_SECOND_PER_CRYSTAL * stakedNFTsAndTokens[owner].numFullCrystalsStaked; // Note: Growing crystals do not accumulate rewards return rewardsAccumulated; } // Do the internal accounting update for the address function _updateRewards(address owner) internal { // First, see if we need to add an epoch. // We may not always need to, especially if the time elapsed is 0 (i.e., multiple tx in same block) if (block.timestamp > lastEpochTime) { _addEpoch(); } // Mark as claimed till the newly created epoch. uint256 lastClaimedEpoch = stakedNFTsAndTokens[owner].lastClaimEpoch; stakedNFTsAndTokens[owner].lastClaimEpoch = uint32(epochs.length - 1); // If this owner is new, just return if (lastClaimedEpoch == 0) { return; } uint256 rewardsAccumulated = _getRewardsAccumulated(owner, lastClaimedEpoch); // Accumulate everything stakedNFTsAndTokens[owner].claimedSpiralBits += uint96(rewardsAccumulated); } // ------------------- // Rewards Epochs // ------------------- // Rewards for ERC20 tokens are different from Rewards for NFTs. // Staked NFTs earn a fixed reward per time, but staked ERC20 earn a reward // proportional to how many other ERC20 of the same type are staked. // That is, there is a global emission per ERC20, that is split evenly among all // staked ERC20. // Therefore, we need to track how many of the total ERC20s were staked for each epoch // Note that if the amount of ERC20 staked by a user changes (via deposit or withdraw), then // the user's balance needs to be updated function _getNextEpoch() internal view returns (RewardEpoch memory) { RewardEpoch memory newEpoch = RewardEpoch({ epochDurationSec: uint32(block.timestamp) - lastEpochTime, totalSpiralBitsStaked: uint96(spiralbits.balanceOf(address(this))), totalImpishStaked: uint96(impish.balanceOf(address(this))) }); return newEpoch; } // Add a new epoch with the balances in the contract function _addEpoch() internal { // Sanity check. Can't add epoch without having the epochs up-to-date require(uint32(block.timestamp) > lastEpochTime, "TooNew"); RewardEpoch memory newEpoch = _getNextEpoch(); // Add to array lastEpochTime = uint32(block.timestamp); epochs.push(newEpoch); } // ------------------- // Keep track of staked NFTs // ------------------- function _totalTokenCountStaked(address _owner) internal view returns (uint256) { return stakedNFTsAndTokens[_owner].numRWStaked + stakedNFTsAndTokens[_owner].numSpiralsStaked + stakedNFTsAndTokens[_owner].numGrowingCrystalsStaked + stakedNFTsAndTokens[_owner].numFullCrystalsStaked; } // Returns a list of token Ids owned by _owner. function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = _totalTokenCountStaked(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } uint256[] memory result = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { result[i] = tokenOfOwnerByIndex(_owner, i); } return result; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) { require(index < _totalTokenCountStaked(owner), "OwnerIndex out of bounds"); return stakedNFTsAndTokens[owner].ownedTokens[index]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param owner address representing the 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 owner, uint256 tokenId) private { uint256 length = _totalTokenCountStaked(owner); stakedNFTsAndTokens[owner].ownedTokens[length] = tokenId; stakedTokenOwners[tokenId].ownedTokensIndex = length; } /** * @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 = _totalTokenCountStaked(from) - 1; uint256 tokenIndex = stakedTokenOwners[tokenId].ownedTokensIndex; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = stakedNFTsAndTokens[from].ownedTokens[lastTokenIndex]; stakedNFTsAndTokens[from].ownedTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token stakedTokenOwners[lastTokenId].ownedTokensIndex = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete stakedTokenOwners[tokenId]; delete stakedNFTsAndTokens[from].ownedTokens[lastTokenIndex]; } // ----------------- // Harvesting and Growing Crystals // ----------------- function setCrystalTargetSym(uint32 crystalTokenId, uint8 targetSym) external nonReentrant { uint32 contractCrystalTokenId = crystalTokenId + 3_000_000; require(stakedTokenOwners[contractCrystalTokenId].owner == msg.sender, "NotYourCrystal"); crystalTargetSyms[contractCrystalTokenId] = targetSym; } // Grow all the given crystals to max size for the target symmetry function _growCrystals(uint32[] memory contractCrystalTokenIds) internal { // How many spiralbits are available to grow uint96 availableSpiralBits = stakedNFTsAndTokens[msg.sender].claimedSpiralBits; stakedNFTsAndTokens[msg.sender].claimedSpiralBits = 0; spiralbits.mintSpiralBits(address(this), availableSpiralBits); for (uint256 i = 0; i < contractCrystalTokenIds.length; i++) { uint32 contractCrystalTokenId = contractCrystalTokenIds[i]; uint32 crystalTokenId = contractCrystalTokenId - 3_000_000; require(stakedTokenOwners[contractCrystalTokenId].owner == msg.sender, "NotYourCrystal"); // Grow the crystal to max that it can (uint8 currentCrystalSize, , uint8 currentSym, , ) = crystals.crystals(crystalTokenId); if (currentCrystalSize < 100) { uint96 spiralBitsNeeded = uint96( crystals.SPIRALBITS_PER_SYM_PER_SIZE() * uint256(100 - currentCrystalSize) * uint256(currentSym) ); if (availableSpiralBits > spiralBitsNeeded) { crystals.grow(crystalTokenId, 100 - currentCrystalSize); availableSpiralBits -= spiralBitsNeeded; } } // Next grow syms if (crystalTargetSyms[contractCrystalTokenId] > 0 && crystalTargetSyms[contractCrystalTokenId] > currentSym) { uint8 growSyms = crystalTargetSyms[contractCrystalTokenId] - currentSym; uint96 spiralBitsNeeded = uint96(crystals.SPIRALBITS_PER_SYM() * uint256(growSyms)); if (availableSpiralBits > spiralBitsNeeded) { crystals.addSym(crystalTokenId, growSyms); availableSpiralBits -= spiralBitsNeeded; } } // And then grow the Crystal again to max size if possible (currentCrystalSize, , currentSym, , ) = crystals.crystals(crystalTokenId); if (currentCrystalSize < 100) { uint96 spiralBitsNeeded = uint96( crystals.SPIRALBITS_PER_SYM_PER_SIZE() * uint256(100 - currentCrystalSize) * uint256(currentSym) ); if (availableSpiralBits > spiralBitsNeeded) { crystals.grow(crystalTokenId, 100 - currentCrystalSize); availableSpiralBits -= spiralBitsNeeded; } } delete crystalTargetSyms[contractCrystalTokenId]; } // Burn any unused spiralbits and credit the user back, so we can harvest more crystals // instead of returning a large amount of SPIRALBITS back to the user here. spiralbits.burn(availableSpiralBits); stakedNFTsAndTokens[msg.sender].claimedSpiralBits = availableSpiralBits; } function harvestCrystals(uint32[] calldata contractCrystalTokenIds, bool claim) external nonReentrant { _updateRewards(msg.sender); // First, grow all the crystals _growCrystals(contractCrystalTokenIds); // And then transfer the crystals over from growing to staked for (uint256 i = 0; i < contractCrystalTokenIds.length; i++) { uint32 contractCrystalTokenId = contractCrystalTokenIds[i]; uint32 crystalTokenId = contractCrystalTokenId - 3_000_000; (uint8 currentCrystalSize, , , , ) = crystals.crystals(crystalTokenId); // Move this crystal over to be staked only if it is fully grown if (currentCrystalSize == 100) { // Unstake growing crystal _removeTokenFromOwnerEnumeration(msg.sender, contractCrystalTokenId); stakedNFTsAndTokens[msg.sender].numGrowingCrystalsStaked -= 1; // Stake fully grown crystal uint256 contractFullyGrownTokenId = 4_000_000 + crystalTokenId; _addTokenToOwnerEnumeration(msg.sender, contractFullyGrownTokenId); stakedTokenOwners[contractFullyGrownTokenId].owner = msg.sender; stakedNFTsAndTokens[msg.sender].numFullCrystalsStaked += 1; } } if (claim) { _claimRewards(msg.sender); } } // ----------------- // RPS Functions // ----------------- // Note that this function is not nonReentrant because the RPS.commit will // reenter via stakeNFTs, and that's OK. function rpsCommit(bytes32 commitment, uint32[] calldata crystalIDs) external { require(rps != address(0), "RPSNotSet"); // Update the owner's rewards first. This also updates the current epoch. _updateRewards(msg.sender); // Unstake the crystals for (uint256 i = 0; i < crystalIDs.length; i++) { uint256 contractTokenId = 4_000_000 + uint256(crystalIDs[i]); require(stakedTokenOwners[contractTokenId].owner == msg.sender, "DontOwnNFT"); _removeTokenFromOwnerEnumeration(msg.sender, contractTokenId); stakedNFTsAndTokens[msg.sender].numFullCrystalsStaked -= 1; } // Commit it for the player IRPS(rps).commit(commitment, msg.sender, crystalIDs); } function setRPS(address _rps) external onlyOwner { rps = _rps; // Authorize the rps to move out Crystals for the RPS game crystals.setApprovalForAll(rps, true); } // ------------------ // Other functions // ------------------ function claimSpiralWin(uint256 spiralTokenId) external nonReentrant { ImpishSpiral(address(impishspiral)).claimWin(spiralTokenId); // Send the ether to the Spiral's owner address spiralOwner = stakedTokenOwners[spiralTokenId + 2_000_000].owner; (bool success, ) = spiralOwner.call{value: address(this).balance}(""); require(success, "Transfer failed."); } receive() external payable { // Default payable to accept ether payments for winning spirals } // ------------------- // Overrides that allow accepting NFTs and ERC20s // ------------------- // Function that marks this contract can accept incoming NFT transfers function onERC721Received( address, address, uint256, bytes calldata ) public pure returns (bytes4) { // Return this value to accept the NFT return IERC721ReceiverUpgradeable.onERC721Received.selector; } }
* @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/ 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). When the token to delete is the last token, the swap operation is unnecessary
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = _totalTokenCountStaked(from) - 1; uint256 tokenIndex = stakedTokenOwners[tokenId].ownedTokensIndex; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = stakedNFTsAndTokens[from].ownedTokens[lastTokenIndex]; } delete stakedNFTsAndTokens[from].ownedTokens[lastTokenIndex]; }
12,845,844
[ 1, 6014, 445, 358, 1206, 279, 1147, 628, 333, 2710, 1807, 23178, 17, 6440, 501, 12597, 18, 3609, 716, 1323, 326, 1147, 353, 486, 6958, 279, 394, 3410, 16, 326, 1375, 67, 995, 329, 5157, 1016, 68, 2874, 353, 389, 902, 67, 3526, 30, 333, 5360, 364, 16189, 5213, 7089, 425, 18, 75, 18, 1347, 14928, 279, 7412, 1674, 261, 842, 839, 310, 1645, 7262, 2934, 1220, 711, 531, 12, 21, 13, 813, 21610, 16, 1496, 524, 5432, 326, 1353, 434, 326, 389, 995, 329, 5157, 526, 18, 225, 628, 1758, 5123, 326, 2416, 3410, 434, 326, 864, 1147, 1599, 225, 1147, 548, 2254, 5034, 1599, 434, 326, 1147, 358, 506, 3723, 628, 326, 2430, 666, 434, 326, 864, 1758, 19, 2974, 5309, 279, 9300, 316, 628, 1807, 2430, 526, 16, 732, 1707, 326, 1142, 1147, 316, 326, 770, 434, 326, 1147, 358, 1430, 16, 471, 1508, 1430, 326, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 225, 445, 389, 4479, 1345, 1265, 5541, 21847, 12, 2867, 628, 16, 2254, 5034, 1147, 548, 13, 3238, 288, 203, 203, 565, 2254, 5034, 27231, 1016, 273, 389, 4963, 1345, 1380, 510, 9477, 12, 2080, 13, 300, 404, 31, 203, 565, 2254, 5034, 1147, 1016, 273, 384, 9477, 1345, 5460, 414, 63, 2316, 548, 8009, 995, 329, 5157, 1016, 31, 203, 203, 565, 309, 261, 2316, 1016, 480, 27231, 1016, 13, 288, 203, 1377, 2254, 5034, 27231, 548, 273, 384, 9477, 50, 4464, 87, 1876, 5157, 63, 2080, 8009, 995, 329, 5157, 63, 2722, 1345, 1016, 15533, 203, 203, 565, 289, 203, 203, 565, 1430, 384, 9477, 50, 4464, 87, 1876, 5157, 63, 2080, 8009, 995, 329, 5157, 63, 2722, 1345, 1016, 15533, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; /* * * Domain on day 1: https://etherbonds.io/ * * This contract implements bond contracts on the Ethereum blockchain * - You can buy a bond for ETH (NominalPrice) * - While buying you can set a desirable MaturityDate * - After you reach the MaturityDate you can redeem the bond for the MaturityPrice * - MaturityPrice is always greater than the NominalPrice * - greater the MaturityDate = higher profit * - You can't redeem a bond after MaxRedeemTime * * For example, you bought a bond for 1 ETH which will mature in 1 month for 63% profit. * After the month you can redeem the bond and receive your 1.63 ETH. * * If you don't want to wait for your bond maturity you can sell it to another investor. * For example you bought a 1 year bond, 6 months have passed and you urgently need money. * You can sell the bond on a secondary market to other investors before the maturity date. * You can also redeem your bond prematurely but only for a part of the nominal price. * * !!! THIS IS A HIGH RISK INVESTMENT ASSET !!! * !!! THIS IS GAMBLING !!! * !!! THIS IS A PONZI SCHEME !!! * All funds invested are going to prev investors for the exception of FounderFee and AgentFee * * Bonds are generating profit due to NEW and NEW investors BUYING them * If the contract has no ETH in it you will FAIL to redeem your bond * However as soon as new bonds will be issued the contract will receive ETH and * you will be able to redeem the bond. * * You can also refer a friend for 10% of the bonds he buys. Your friend will also receive a referral bonus for trading with your code! * */ /* * ------------------------------ * Main functions are: * Buy() - to buy a new issued bond * Redeem() - to redeem your bond for profit * * BuyOnSecondaryMarket() - to buy a bond from other investors * PlaceSellOrder() - to place your bond on the secondary market for selling * CancelSellOrder() - stop selling your bond * Withdraw() - to withdraw agant commission or funds after selling a bond on the secondary market * ------------------------------ */ /** /* Math operations with safety checks */ contract SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function assert(bool assertion) internal pure { if (!assertion) { revert(); } } } contract EtherBonds is SafeMath { /* A founder can write here useful information */ /* For example current domain name or report a problem */ string public README = "STATUS_OK"; /* You can refer a friend and you will be receiving a bonus for EACH his deal */ /* The friend will also have a bonus but only once */ /* You should have at least one bond in your history to be an agent */ /* Just ask your friend to specify your wallet address with his FIRST deal */ uint32 AgentBonusInPercent = 10; /* A user gets a bonus for adding an agent for his first deal */ uint32 UserRefBonusInPercent = 3; /* How long it takes for a bond to mature */ uint32 MinMaturityTimeInDays = 30; // don't set less than 15 days uint32 MaxMaturityTimeInDays = 240; /* Minimum price of a bond */ uint MinNominalBondPrice = 0.006 ether; /* How much % of your bond you can redeem prematurely */ uint32 PrematureRedeemPartInPercent = 25; /* How much this option costs */ uint32 PrematureRedeemCostInPercent = 20; /* Be careful! */ /* If you don't redeem your bond AFTER its maturity date */ /* the bond will become irredeemable! */ uint32 RedeemRangeInDays = 1; uint32 ExtraRedeemRangeInDays = 3; /* However you can prolong your redeem period for a price */ uint32 ExtraRedeemRangeCostInPercent = 10; /* Founder takes a fee for each bond sold */ /* There is no way for a founder to take all the contract's money, fonder takes only the fee */ address public Founder; uint32 public FounderFeeInPercent = 5; /* Events */ event Issued(uint32 bondId, address owner); event Sold(uint32 bondId, address seller, address buyer, uint price); event SellOrderPlaced(uint32 bondId, address seller); event SellOrderCanceled(uint32 bondId, address seller); event Redeemed(uint32 bondId, address owner); struct Bond { /* Unique ID of a bond */ uint32 id; address owner; uint32 issueTime; uint32 maturityTime; uint32 redeemTime; /* A bond can't be redeemed after this date */ uint32 maxRedeemTime; bool canBeRedeemedPrematurely; uint nominalPrice; uint maturityPrice; /* You can resell your bond to another user */ uint sellingPrice; } uint32 NextBondID = 1; mapping(uint32 => Bond) public Bonds; struct UserInfo { /* This address will receive commission for this user trading */ address agent; uint32 totalBonds; mapping(uint32 => uint32) bonds; } mapping(address => UserInfo) public Users; mapping(address => uint) public Balances; /* MAIN */ function EtherBonds() public { Founder = msg.sender; } function ContractInfo() public view returns( string readme, uint32 agentBonusInPercent, uint32 userRefBonusInPercent, uint32 minMaturityTimeInDays, uint32 maxMaturityTimeInDays, uint minNominalBondPrice, uint32 prematureRedeemPartInPercent, uint32 prematureRedeemCostInPercent, uint32 redeemRangeInDays, uint32 extraRedeemRangeInDays, uint32 extraRedeemRangeCostInPercent, uint32 nextBondID, uint balance ) { readme = README; agentBonusInPercent = AgentBonusInPercent; userRefBonusInPercent = UserRefBonusInPercent; minMaturityTimeInDays = MinMaturityTimeInDays; maxMaturityTimeInDays = MaxMaturityTimeInDays; minNominalBondPrice = MinNominalBondPrice; prematureRedeemPartInPercent = PrematureRedeemPartInPercent; prematureRedeemCostInPercent = PrematureRedeemCostInPercent; redeemRangeInDays = RedeemRangeInDays; extraRedeemRangeInDays = ExtraRedeemRangeInDays; extraRedeemRangeCostInPercent = ExtraRedeemRangeCostInPercent; nextBondID = NextBondID; balance = this.balance; } /* This function calcs how much profit will a bond bring */ function MaturityPrice( uint nominalPrice, uint32 maturityTimeInDays, bool hasExtraRedeemRange, bool canBeRedeemedPrematurely, bool hasRefBonus ) public view returns(uint) { uint nominalPriceModifierInPercent = 100; if (hasExtraRedeemRange) { nominalPriceModifierInPercent = sub( nominalPriceModifierInPercent, ExtraRedeemRangeCostInPercent ); } if (canBeRedeemedPrematurely) { nominalPriceModifierInPercent = sub( nominalPriceModifierInPercent, PrematureRedeemCostInPercent ); } if (hasRefBonus) { nominalPriceModifierInPercent = add( nominalPriceModifierInPercent, UserRefBonusInPercent ); } nominalPrice = div( mul(nominalPrice, nominalPriceModifierInPercent), 100 ); //y = 1.177683 - 0.02134921*x + 0.001112346*x^2 - 0.000010194*x^3 + 0.00000005298844*x^4 /* 15days +7% 30days +30% 60days +138% 120days +700% 240days +9400% */ uint x = maturityTimeInDays; /* The formula will break if x < 15 */ require(x >= 15); var a = mul(2134921000, x); var b = mul(mul(111234600, x), x); var c = mul(mul(mul(1019400, x), x), x); var d = mul(mul(mul(mul(5298, x), x), x), x); var k = sub(sub(add(add(117168300000, b), d), a), c); k = div(k, 10000000); return div(mul(nominalPrice, k), 10000); } /* This function checks if you can change your bond back to money */ function CanBeRedeemed(Bond bond) internal view returns(bool) { return bond.issueTime > 0 && // a bond should be issued bond.owner != 0 && // it should should have an owner bond.redeemTime == 0 && // it should not be already redeemed bond.sellingPrice == 0 && // it should not be reserved for selling ( !IsPremature(bond.maturityTime) || // it should be mature / be redeemable prematurely bond.canBeRedeemedPrematurely ) && block.timestamp <= bond.maxRedeemTime; // be careful, you can't redeem too old bonds } /* For some external checkings we gonna to wrap this in a function */ function IsPremature(uint maturityTime) public view returns(bool) { return maturityTime > block.timestamp; } /* This is how you buy bonds on the primary market */ function Buy( uint32 maturityTimeInDays, bool hasExtraRedeemRange, bool canBeRedeemedPrematurely, address agent // you can leave it 0 ) public payable { /* We don't issue bonds cheaper than MinNominalBondPrice*/ require(msg.value >= MinNominalBondPrice); /* We don't issue bonds out of allowed maturity range */ require( maturityTimeInDays >= MinMaturityTimeInDays && maturityTimeInDays <= MaxMaturityTimeInDays ); /* You can have a bonus on your first deal if specify an agent */ bool hasRefBonus = false; /* On your first deal ... */ if (Users[msg.sender].agent == 0 && Users[msg.sender].totalBonds == 0) { /* ... you may specify an agent and get a bonus for this ... */ if (agent != 0) { /* ... the agent should have some bonds behind him */ if (Users[agent].totalBonds > 0) { Users[msg.sender].agent = agent; hasRefBonus = true; } else { agent = 0; } } } /* On all your next deals you will have the same agent as on the first one */ else { agent = Users[msg.sender].agent; } /* Issuing a new bond */ Bond memory newBond; newBond.id = NextBondID; newBond.owner = msg.sender; newBond.issueTime = uint32(block.timestamp); newBond.canBeRedeemedPrematurely = canBeRedeemedPrematurely; /* You cant redeem your bond for profit untill this date */ newBond.maturityTime = newBond.issueTime + maturityTimeInDays*24*60*60; /* Your time to redeem is limited */ newBond.maxRedeemTime = newBond.maturityTime + (hasExtraRedeemRange?ExtraRedeemRangeInDays:RedeemRangeInDays)*24*60*60; newBond.nominalPrice = msg.value; newBond.maturityPrice = MaturityPrice( newBond.nominalPrice, maturityTimeInDays, hasExtraRedeemRange, canBeRedeemedPrematurely, hasRefBonus ); Bonds[newBond.id] = newBond; NextBondID += 1; /* Linking the bond to the owner so later he can easily find it */ var user = Users[newBond.owner]; user.bonds[user.totalBonds] = newBond.id; user.totalBonds += 1; /* Notify all users about the issuing event */ Issued(newBond.id, newBond.owner); /* Founder's fee */ uint moneyToFounder = div( mul(newBond.nominalPrice, FounderFeeInPercent), 100 ); /* Agent bonus */ uint moneyToAgent = div( mul(newBond.nominalPrice, AgentBonusInPercent), 100 ); if (agent != 0 && moneyToAgent > 0) { /* Agent can potentially block user's trading attempts, so we dont use just .transfer*/ Balances[agent] = add(Balances[agent], moneyToAgent); } /* Founder always gets his fee */ require(moneyToFounder > 0); Founder.transfer(moneyToFounder); } /* You can also buy bonds on secondary market from other users */ function BuyOnSecondaryMarket(uint32 bondId) public payable { var bond = Bonds[bondId]; /* A bond you are buying should be issued */ require(bond.issueTime > 0); /* Checking, if the bond is a valuable asset */ require(bond.redeemTime == 0 && block.timestamp < bond.maxRedeemTime); var price = bond.sellingPrice; /* You can only buy a bond if an owner is selling it */ require(price > 0); /* You should have enough money to pay the owner */ require(price <= msg.value); /* It's ok if you accidentally transfer more money, we will send them back */ var residue = msg.value - price; /* Transfering the bond */ var oldOwner = bond.owner; var newOwner = msg.sender; require(newOwner != 0 && newOwner != oldOwner); bond.sellingPrice = 0; bond.owner = newOwner; var user = Users[bond.owner]; user.bonds[user.totalBonds] = bond.id; user.totalBonds += 1; /* Doublechecking the price */ require(add(price, residue) == msg.value); /* Notify all users about the exchange event */ Sold(bond.id, oldOwner, newOwner, price); /* Old owner can potentially block user's trading attempts, so we dont use just .transfer*/ Balances[oldOwner] = add(Balances[oldOwner], price); if (residue > 0) { /* If there is residue we will send it back */ newOwner.transfer(residue); } } /* You can sell your bond on the secondary market */ function PlaceSellOrder(uint32 bondId, uint sellingPrice) public { /* To protect from an accidental selling by 0 price */ /* The selling price should be in Wei */ require(sellingPrice >= MinNominalBondPrice); var bond = Bonds[bondId]; /* A bond you are selling should be issued */ require(bond.issueTime > 0); /* You can't update selling price, please, call CancelSellOrder beforehand */ require(bond.sellingPrice == 0); /* You can't sell useless bonds */ require(bond.redeemTime == 0 && block.timestamp < bond.maxRedeemTime); /* You should own a bond you're selling */ require(bond.owner == msg.sender); bond.sellingPrice = sellingPrice; /* Notify all users about you wanting to sell the bond */ SellOrderPlaced(bond.id, bond.owner); } /* You can cancel your sell order */ function CancelSellOrder(uint32 bondId) public { var bond = Bonds[bondId]; /* Bond should be reserved for selling */ require(bond.sellingPrice > 0); /* You should own a bond which sell order you're cancelling */ require(bond.owner == msg.sender); bond.sellingPrice = 0; /* Notify all users about cancelling the selling order */ SellOrderCanceled(bond.id, bond.owner); } /* Sometimes we can't just use .transfer for a security reason */ function Withdraw() public { require(Balances[msg.sender] > 0); /* Don't forget about double entering in .transfer! */ var money = Balances[msg.sender]; Balances[msg.sender] = 0; msg.sender.transfer(money); } /* You can redeem bonds back to the contract for profit */ /* But you need to wait till maturityTime */ /* This is the key function where you get profit for a bond you own */ function Redeem(uint32 bondId) public { var bond = Bonds[bondId]; require(CanBeRedeemed(bond)); /* You should own a bond you redeem */ require(bond.owner == msg.sender); /* If a bond has redeemTime it has been redeemed */ bond.redeemTime = uint32(block.timestamp); /* If it's a premature redeem you will only get PrematureRedeemPartInPercent of nominalPrice back */ if (IsPremature(bond.maturityTime)) { bond.maturityPrice = div( mul(bond.nominalPrice, PrematureRedeemPartInPercent), 100 ); } /* Notify all users about the redeem event */ Redeemed(bond.id, bond.owner); /* Transfer funds to the owner */ /* This is how you earn money */ bond.owner.transfer(bond.maturityPrice); } /* Be carefull, this function can return a bound of a differet owner if the bond was sold. Always check the bond owner */ function UserBondByOffset(uint32 offset) public view returns( uint32 bondId, bool canBeRedeemed, bool isPremature ) { var bond = Bonds[Users[msg.sender].bonds[offset]]; bondId = bond.id; canBeRedeemed = CanBeRedeemed(bond); isPremature = IsPremature(bond.maturityTime); } function BondInfoById(uint32 bondId) public view returns( bool canBeRedeemed, bool isPremature ) { var bond = Bonds[bondId]; canBeRedeemed = CanBeRedeemed(bond); isPremature = IsPremature(bond.maturityTime); } /* ADMIN */ function AdmChange_README(string value) public { require(msg.sender == Founder); README = value; } }
Transfer funds to the owner */ This is how you earn money */
bond.owner.transfer(bond.maturityPrice);
5,401,629
[ 1, 5912, 284, 19156, 358, 326, 3410, 342, 1220, 353, 3661, 1846, 425, 1303, 15601, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 8427, 18, 8443, 18, 13866, 12, 26425, 18, 7373, 2336, 5147, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xD05BF5b36Be1fcDB5c1F7fEADaE53646faA169DE/sources/contracts/bases/ToucanCarbonOffsetsWithBatchBase.sol
Finalize escrow request
IToucanCarbonOffsetsEscrow(escrow).finalizeRequest(requestId);
9,439,337
[ 1, 7951, 554, 2904, 492, 590, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 467, 774, 89, 4169, 39, 11801, 13830, 6412, 492, 12, 742, 492, 2934, 30343, 691, 12, 2293, 548, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; interface ICalculator { function price() external view returns (uint256); } contract TBDPass is ERC1155, Ownable, ReentrancyGuard { using ECDSA for bytes32; // - events event BurnerStateChanged(address indexed burner, bool indexed newState); event ContractToggled(bool indexed newState); event FloatingCapUpdated(uint256 indexed newCap); event PriceCalculatorUpdated(address indexed calc); event VerifiedSignerSet(address indexed signer); // - constants uint256 public constant PASS_ID = 0; uint256 public constant STAGE1_CAP = 2000; // initial floating cap uint256 public constant RESERVE_CAP = 2000; // global limit on the tokens mintable by owner uint256 public constant HARD_CAP = 10000; // global limit on the tokens mintable by anyone uint256 public constant MAX_MINT = 250; // global per-account limit of mintable tokens uint256 public constant PRICE = .06 ether; // initial token price uint256 public constant PRICE_INCREMENT = .05 ether; // increment it by this amount uint256 public constant PRICE_TIER_SIZE = 500; // every ... tokens address private constant TIP_RECEIVER = 0x3a6E4D326aeb315e85E3ac0A918361672842a496; // // - storage variables; uint256 public totalSupply; // all tokens minted uint256 public reserveSupply; // minted by owner; never exceeds RESERVE_CAP uint256 public reserveSupplyThisPeriod; // minted by owner this release period, never exceeds reserveCap uint256 public reserveCapThisPeriod; // current reserve cap; never exceeds RESERVE_CAP - reserveSupply uint256 public floatingCap; // current upper boundary of the floating cap; never exceeds HARD_CAP uint256 public releasePeriod; // counter of floating cap updates; changing this invalidates wl signatures bool public paused; // control wl minting and at-cost minting address public verifiedSigner; // wl requests must be signed by this account ICalculator public calculator; // external price source mapping(address => bool) public burners; // accounts allowed to burn tokens mapping(uint256 => mapping(address => uint256)) public allowances; // tracked wl allowances for current release cycle mapping(address => uint256) public mints; // lifetime accumulators for tokens minted constructor() ERC1155("https://studio-tbd.io/tokens/default.json") { floatingCap = STAGE1_CAP; } function price() external view returns (uint256) { return _price(); } function getAllowance() external view returns (uint256) { uint256 allowance = allowances[releasePeriod][msg.sender]; if (allowance > 1) { return allowance - 1; } else { return 0; } } function whitelistMint( uint256 qt, uint256 initialAllowance, bytes calldata signature ) external { _whenNotPaused(); // Signatures from previous `releasePeriod`s will not check out. _validSignature(msg.sender, initialAllowance, signature); // Set account's allowance on first use of the signature. // The +1 offset allows to distinguish between a) first-time // call; and b) fully claimed allowance. If the first use tx // executes successfully, ownce never goes below 1. mapping(address => uint256) storage ownce = allowances[releasePeriod]; if (ownce[msg.sender] == 0) { ownce[msg.sender] = initialAllowance + 1; } // The actual allowance is always ownce -1; // must be above 0 to proceed. uint256 allowance = ownce[msg.sender] - 1; require(allowance > 0, "OutOfAllowance"); // If the qt requested is 0, mint up to max allowance: uint256 qt_ = (qt == 0)? allowance : qt; // qt_ is never 0, since if it's 0, it assumes allowance, // and that would revert earlier if 0. assert(qt_ > 0); // It is possible, however, that qt is non-zero and exceeds allowance: require(qt_ <= allowance, "MintingExceedsAllowance"); // Observe lifetime per-account limit: require(qt_ + mints[msg.sender] <= MAX_MINT, "MintingExceedsLifetimeLimit"); // In order to assess whether it's cool to extend the floating cap by qt_, // calculate the extension upper bound. The gist: extend as long as // the team's reserve is guarded. uint256 reserveVault = (RESERVE_CAP - reserveSupply) - (reserveCapThisPeriod - reserveSupplyThisPeriod); uint256 extensionMintable = HARD_CAP - floatingCap - reserveVault; // split between over-the-cap supply and at-cost supply uint256 mintableAtCost = _mintableAtCost(); uint256 wlMintable = extensionMintable + mintableAtCost; require(qt_ <= wlMintable, "MintingExceedsAvailableSupply"); // adjust fc floatingCap += (qt_ > extensionMintable)? extensionMintable : qt_; // decrease caller's allowance in the current period ownce[msg.sender] -= qt_; _mintN(msg.sender, qt_); } function mint(uint256 qt) external payable { _whenNotPaused(); require(qt > 0, "ZeroTokensRequested"); require(qt <= _mintableAtCost(), "MintingExceedsFloatingCap"); require( mints[msg.sender] + qt <= MAX_MINT, "MintingExceedsLifetimeLimit" ); require(qt * _price() == msg.value, "InvalidETHAmount"); _mintN(msg.sender, qt); } function withdraw() external { _onlyOwner(); uint256 tip = address(this).balance * 2 / 100; payable(TIP_RECEIVER).transfer(tip); payable(owner()).transfer(address(this).balance); } function setCalculator(address calc) external { _onlyOwner(); require(calc != address(0), "ZeroCalculatorAddress"); emit PriceCalculatorUpdated(calc); calculator = ICalculator(calc); } function setVerifiedSigner(address signer) external { _onlyOwner(); require(signer != address(0), "ZeroSignerAddress"); emit VerifiedSignerSet(signer); verifiedSigner = signer; } function setFloatingCap(uint256 cap, uint256 reserve) external { _onlyOwner(); require(reserveSupply + reserve <= RESERVE_CAP, "OwnerReserveExceeded"); require(cap >= floatingCap, "CapUnderCurrentFloatingCap"); require(cap <= HARD_CAP, "HardCapExceeded"); require((RESERVE_CAP - reserveSupply - reserve) <= (HARD_CAP - cap), "OwnerReserveViolation"); require(cap - totalSupply >= reserve, "ReserveExceedsTokensAvailable"); reserveCapThisPeriod = reserve; reserveSupplyThisPeriod = 0; emit FloatingCapUpdated(cap); floatingCap = cap; _nextPeriod(); } function reduceReserve(uint256 to) external { _onlyOwner(); require(to >= reserveSupplyThisPeriod, "CannotDecreaseBelowMinted"); require(to < reserveCapThisPeriod, "CannotIncreaseReserve"); // supply above floatingCap must be still sufficient to compensate // for potentially excessive reduction uint256 capExcess = HARD_CAP - floatingCap; bool reserveViolated = capExcess < (RESERVE_CAP - reserveSupply) - (to - reserveSupplyThisPeriod); require(!reserveViolated, "OwnerReserveViolation"); reserveCapThisPeriod = to; } function nextPeriod() external { _onlyOwner(); _nextPeriod(); } function setBurnerState(address burner, bool state) external { _onlyOwner(); require(burner != address(0), "ZeroBurnerAddress"); emit BurnerStateChanged(burner, state); burners[burner] = state; } function burn(address holder, uint256 qt) external { _onlyBurners(); _burn(holder, PASS_ID, qt); _mint(0x000000000000000000000000000000000000dEaD, PASS_ID, qt, ""); } function setURI(string memory uri_) external { _onlyOwner(); _setURI(uri_); } function toggle() external { _onlyOwner(); emit ContractToggled(!paused); paused = !paused; } function teamdrop(address to, uint256 qt) external { _onlyOwner(); require(to != address(0), "ZeroReceiverAddress"); require(qt > 0, "ZeroTokensRequested"); require(releasePeriod > 0, "PrematureMintingByOwner"); require(reserveSupplyThisPeriod + qt <= reserveCapThisPeriod, "MintingExceedsPeriodReserve"); reserveSupply += qt; reserveSupplyThisPeriod += qt; _mintN(to, qt); } // - internals function _nextPeriod() internal { releasePeriod++; } function _mintN(address to, uint256 qt) internal nonReentrant { totalSupply += qt; mints[to] += qt; _mint(to, PASS_ID, qt, ""); } function _mintableAtCost() internal view returns (uint256) { return floatingCap - totalSupply - (reserveCapThisPeriod - reserveSupplyThisPeriod); } function _onlyOwner() internal view { require(msg.sender == owner(), "UnauthorizedAccess"); } function _onlyBurners() internal view { require(burners[msg.sender], "UnauthorizedAccess"); } function _whenNotPaused() internal view { require(!paused, "ContractPaused"); } function _validSignature( address account, uint256 allowance, bytes calldata signature ) internal view { bytes32 hash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(account, releasePeriod, allowance)) ) ); require( hash.recover(signature) == verifiedSigner, "InvalidSignature." ); } function _price() internal view returns (uint256 price_) { if (calculator != ICalculator(address(0))) { price_ = calculator.price(); } else { price_ = PRICE + PRICE_INCREMENT * (totalSupply / PRICE_TIER_SIZE); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // 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 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override 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), "ERC1155: balance query for the zero address"); 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 virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); 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 { _setApprovalForAll(_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 { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `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 memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - 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[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[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 ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @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, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @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 _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.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 IERC1155MetadataURI is IERC1155 { /** * @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 // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.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. 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 // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) 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 // 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); }
If the qt requested is 0, mint up to max allowance:
uint256 qt_ = (qt == 0)? allowance : qt;
11,927,722
[ 1, 2047, 326, 25672, 3764, 353, 374, 16, 312, 474, 731, 358, 943, 1699, 1359, 30, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 25672, 67, 273, 261, 23311, 422, 374, 9945, 1699, 1359, 294, 25672, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x7615E5B102D74deF17F73d1620Aa5c8709Ea61cf/sources/TwoSwords.sol
Original Fee2% max wallet and max transaction
contract TwoSwords is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = unicode"Two Swords Coin"; string private constant _symbol = unicode"⚔️"; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 100000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _redisFeeOnBuy = 0; uint256 private _taxFeeOnBuy = 15; uint256 private _redisFeeOnSell = 0; uint256 private _taxFeeOnSell = 25; uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping (address => uint256) public _buyMap; address payable private _developmentAddress = payable(0x5FdF23dea7d55e8680AAfcBa67772DB65C360362); address payable private _marketingAddress = payable(0x5FdF23dea7d55e8680AAfcBa67772DB65C360362); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen = true; bool private inSwap = false; bool private swapEnabled = true; uint256 public _maxTxAmount = 2000000000 * 10**9; uint256 public _maxWalletSize = 2000000000 * 10**9; uint256 public _swapTokensAtAmount = 20000000 * 10**9; event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } } else { function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _marketingAddress.transfer(amount); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; } function manualswap() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function removeLimits() external onlyOwner { _maxTxAmount = _tTotal; _maxWalletSize = _tTotal; } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount); if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } }
4,030,933
[ 1, 8176, 30174, 22, 9, 943, 9230, 471, 943, 2492, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 16896, 55, 3753, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 533, 3238, 5381, 389, 529, 273, 5252, 6, 11710, 348, 3753, 28932, 14432, 203, 565, 533, 3238, 5381, 389, 7175, 273, 5252, 6, 163, 253, 247, 176, 121, 242, 14432, 203, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 2468, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 15088, 11706, 380, 1728, 636, 29, 31, 203, 565, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 565, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 565, 2254, 5034, 3238, 389, 12311, 14667, 1398, 38, 9835, 273, 374, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 1398, 38, 9835, 273, 4711, 31, 203, 565, 2254, 5034, 3238, 389, 12311, 14667, 1398, 55, 1165, 273, 374, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 1398, 55, 1165, 273, 6969, 31, 203, 203, 565, 2254, 5034, 2 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "deps/@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "deps/@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "deps/@openzeppelin/contracts/math/SafeMath.sol"; import "../../../oracle/interfaces/StoreInterface.sol"; import "../../../oracle/interfaces/OracleInterface.sol"; import "../../../oracle/interfaces/FinderInterface.sol"; import "../../../oracle/interfaces/AdministrateeInterface.sol"; import "../../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../../oracle/interfaces/RegistryInterface.sol"; import "../../../oracle/implementation/Constants.sol"; import "../../perpetual-multiparty/PerpetualInterface.sol"; import "../interfaces/FundingRateStoreInterface.sol"; import "../../../common/implementation/Testable.sol"; import "../../../common/implementation/Lockable.sol"; import "../../../common/implementation/FixedPoint.sol"; /** * @notice FundingRateStore always makes available the current funding rate for a given perpetual contract address. * "Proposers" can update funding rates by proposing a new rate and waiting for a proposal liveness to expire. During * the liveness period, "Disputers" can reject a proposed funding rate and raise a price request against the DVM. * Cash flows as follows in the following actions: * * VARIABLES: * - Final fee bond : a constant value unique for each funding rate identifier and perpetual contract (we assume that * every perpetual is 1-to-1 mapped to a funding rate identifier). * - Proposal bond : the product of the "proposalBondPct" state variable and a given perpetual's PfC at the time of * proposal. * - Dispute bond : same as the proposal bond currently. * - Proposal reward : the product of a given perpetual's PfC and its "reward rate" at the time of * proposal. The reward rate implies that the reward gets larger as time since the last proposal * increases, and also includes a "difference factor" to give more weight to larger funding rate * changes. * * ACTIONS: * - Proposing a new funding rate: * - Proposer pays: (final fee bond) + (proposal bond) * - Store receives: (final fee bond) + (proposal bond) * - Publishing a proposal after its liveness expires: * - Proposer receives: (final fee bond) + (proposal bond) + (proposal reward) * - Perpetual pays: (proposal reward) * - Store pays: (final fee bond) + (proposal bond) * - Disputing a pending proposal: * - Disputer pays: (final fee bond) + (disputer bond) * - Store receives (disputer bond) * - DVM receives (final fee bond) * - Settling a dispute after the DVM resolves its price request: * - Winner of dispute (disputer or proposer) receives: (proposal bond) + (disputer bond) + (final fee bond) * - Store pays: (proposal bond) + (disputer bond) + (final fee bond) */ contract FundingRateStore is FundingRateStoreInterface, Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; using SafeERC20 for IERC20; /**************************************** * STORE DATA STRUCTURES * ****************************************/ FixedPoint.Unsigned public proposalBondPct; // Percentage of 1, e.g. 0.0005 is 0.05% // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; struct Proposal { FixedPoint.Signed rate; uint256 time; address proposer; FixedPoint.Unsigned finalFee; FixedPoint.Unsigned proposalBond; address disputer; FixedPoint.Unsigned rewardRate; } struct FundingRateRecord { FixedPoint.Signed rate; // Current funding rate. uint256 proposeTime; // Time at which current funding rate was proposed. Proposal proposal; FixedPoint.Unsigned rewardRatePerSecond; // Percentage of 1 E.g., .1 is 10%. } enum ProposalState {None, Pending, Expired} mapping(address => FundingRateRecord) private fundingRateRecords; // TODO: Is there any reason to make `fundingRateDisputes` public? Could users use the dispute struct // to get funding rate data "for free"? If not, then I see no harm in making it public. mapping(address => mapping(uint256 => FundingRateRecord)) private fundingRateDisputes; uint256 public proposalLiveness; /**************************************** * EVENTS * ****************************************/ event ChangedRewardRate(address indexed perpetual, uint256 rewardRate); event ProposedRate( address indexed perpetual, int256 rate, uint256 indexed proposalTime, address indexed proposer, uint256 rewardPct, uint256 proposalBond, uint256 finalFeeBond ); event DisputedRate( address indexed perpetual, int256 rate, uint256 indexed proposalTime, address indexed proposer, address disputer, uint256 disputeBond, uint256 finalFeeBond ); event PublishedRate( address indexed perpetual, int256 rate, uint256 indexed proposalTime, address indexed proposer, uint256 rewardPct, uint256 rewardPayment, uint256 totalPayment ); event DisputedRateSettled( address indexed perpetual, uint256 indexed proposalTime, address proposer, address indexed disputer, bool disputeSucceeded ); event FinalFeesPaid(address indexed collateralCurrency, uint256 indexed amount); event WithdrawErrorIgnored(address indexed perpetual, uint256 withdrawAmount); /**************************************** * MODIFIERS * ****************************************/ // Pubishes any pending proposals whose liveness has passed, pays out rewards for such proposals. modifier publishAndWithdrawProposal(address perpetual) { _publishRateAndWithdrawRewards(perpetual); _; } // Function callable only by contracts registered with the DVM. modifier onlyRegisteredContract() { RegistryInterface registry = RegistryInterface(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Caller must be registered"); _; } constructor( uint256 _proposalLiveness, address _finderAddress, address _timerAddress, FixedPoint.Unsigned memory _proposalBondPct ) public Testable(_timerAddress) { require(_proposalLiveness > 0, "Proposal liveness is 0"); proposalLiveness = _proposalLiveness; proposalBondPct = _proposalBondPct; finder = FinderInterface(_finderAddress); } /** * @notice Gets the latest funding rate for a perpetual contract. * @dev This method should never revert. Moreover, because this method is designed to be called by the `perpetual` * contract, it should never make a call back to the `perpetual` contract. Otherwise it will trigger the * `perpetual`'s reentrancy guards and cause the external calls to revert. * @param perpetual perpetual contract whose funding rate identifier that the calling contracts wants to get * a funding rate for. * @return FixedPoint.Signed representing the funding rate for the given contract. 0.01 would represent a funding * rate of 1% per second. -0.01 would represent a negative funding rate of -1% per second. */ function getFundingRateForContract(address perpetual) external override view onlyRegisteredContract() nonReentrantView() returns (FixedPoint.Signed memory) { FundingRateRecord storage fundingRateRecord = _getFundingRateRecord(perpetual); if (_getProposalState(fundingRateRecord.proposal) == ProposalState.Expired) { return fundingRateRecord.proposal.rate; } else { return fundingRateRecord.rate; } } /** * @notice Gets the projected reward % for a successful proposer of a funding rate for a given perpetual contract. * @dev This method is designed to be helpful for proposers in projecting their rewards. The reward % is a function * of the perpetual contract's base reward % per second, the time elapsed since the last proposal, and the * magnitude of change between the proposed and current funding rates. Note that unless the caller calls this * method and proposes a funding rate in the same block, then the projected reward will be slightly underestimated. * Note also that the actual reward is dependent on the perpetual's `PfC` at publish time and this method's * reward %. * @param perpetual Perpetual contract whose reward the caller is querying. * @param rate Proposed rate. * @return rewardRate Representing the reward % for a given contract if they were to propose a funding rate * now. */ function getRewardRateForContract(address perpetual, FixedPoint.Signed memory rate) external view nonReentrantView() returns (FixedPoint.Unsigned memory rewardRate) { FundingRateRecord storage fundingRateRecord = _getFundingRateRecord(perpetual); rewardRate = _calculateProposalRewardPct(perpetual, fundingRateRecord.proposeTime, getCurrentTime(), rate, fundingRateRecord.rate); } /** * @notice Propose a new funding rate for a perpetual. * @dev This will revert if there is already a pending funding rate for the perpetual. * @dev Caller must approve this contract to spend `finalFeeBond` + `proposalBond` amount of collateral, which they can * receive back once their funding rate is published. * @param perpetual Perpetual contract to propose funding rate for. * @param rate Proposed rate. */ function propose(address perpetual, FixedPoint.Signed memory rate) external nonReentrant() publishAndWithdrawProposal(perpetual) { // Ensure that the perpetual's funding rate identifier is whitelisted with the DVM, otherwise disputes on this // proposal would not be possible. require( _getIdentifierWhitelist().isIdentifierSupported(PerpetualInterface(perpetual).getFundingRateIdentifier()), "Unsupported funding identifier" ); FundingRateRecord storage fundingRateRecord = _getFundingRateRecord(perpetual); require(_getProposalState(fundingRateRecord.proposal) != ProposalState.Pending, "Pending proposal exists"); require(!fundingRateRecord.rate.isEqual(rate), "Cannot propose same rate"); uint256 currentTime = getCurrentTime(); // Make sure that there is no disputed proposal for the same perpetual and proposal time. This prevents // the proposer from potentially overwriting a proposal. Note that this would be a rare case in which the // proposer [ (1) created a proposal, (2) disputed the proposal, and (3) created another proposal ] all within // the same block. The proposer would lose their bond from the first proposal forever. require(_getFundingRateDispute(perpetual, currentTime).proposal.proposer == address(0x0), "Proposal pending dispute"); // Compute final fee at time of proposal. IERC20 collateralCurrency = IERC20(PerpetualInterface(perpetual).getCollateralCurrency()); FixedPoint.Unsigned memory finalFeeBond = _computeFinalFees(collateralCurrency); // Calculate and store reward %. Note that because this saved data is a percent, the actual reward // will vary at publish time depending on the `perpetual`'s PfC at that time. FixedPoint.Unsigned memory rewardRate = _calculateProposalRewardPct( perpetual, fundingRateRecord.proposeTime, currentTime, rate, fundingRateRecord.rate ); // Compute proposal bond. FixedPoint.Unsigned memory proposalBond = proposalBondPct.mul(AdministrateeInterface(perpetual).pfc()); // Enqueue proposal. fundingRateRecord.proposal = Proposal({ rate: rate, time: currentTime, proposer: msg.sender, finalFee: finalFeeBond, proposalBond: proposalBond, disputer: address(0x0), rewardRate: rewardRate }); emit ProposedRate(perpetual, rate.rawValue, currentTime, msg.sender, rewardRate.rawValue, proposalBond.rawValue, finalFeeBond.rawValue); // Pull total bond from proposer. collateralCurrency.safeTransferFrom(msg.sender, address(this), proposalBond.add(finalFeeBond).rawValue); } /** * @notice Dispute a pending funding rate. This will delete the pending funding rate, meaning that a * proposer can now propose another rate with a fresh liveness. * @dev This will revert if there is no pending funding rate for the perpetual. * @dev Caller must approve this this contract to spend `finalFeeBond` + `proposalBond` amount of collateral, * which they can receive back if their dispute is successful. * @param perpetual Contract to dispute proposed funding rate for. */ function dispute(address perpetual) external nonReentrant() publishAndWithdrawProposal(perpetual) { FundingRateRecord storage fundingRateRecord = _getFundingRateRecord(perpetual); require(_getProposalState(fundingRateRecord.proposal) == ProposalState.Pending, "No pending proposal"); // Pull proposal bond from disputer and pay DVM store using final fee portion. FixedPoint.Unsigned memory proposalBond = fundingRateRecord.proposal.proposalBond; IERC20 collateralCurrency = IERC20(PerpetualInterface(perpetual).getCollateralCurrency()); collateralCurrency.safeTransferFrom(msg.sender, address(this), proposalBond.rawValue); _payFinalFees(collateralCurrency, msg.sender, fundingRateRecord.proposal.finalFee); // Send price request _requestOraclePrice(PerpetualInterface(perpetual).getFundingRateIdentifier(), fundingRateRecord.proposal.time); emit DisputedRate( perpetual, fundingRateRecord.proposal.rate.rawValue, fundingRateRecord.proposal.time, fundingRateRecord.proposal.proposer, msg.sender, proposalBond.rawValue, fundingRateRecord.proposal.finalFee.rawValue ); // Delete pending proposal and copy into dispute records. fundingRateRecord.proposal.disputer = msg.sender; fundingRateDisputes[perpetual][fundingRateRecord.proposal.time] = fundingRateRecord; delete fundingRateRecords[perpetual].proposal; } /** * @notice Settle a disputed funding rate. The winner of the dispute, either the disputer or the proposer, * will receive a rebate for their bonds plus the losing party's bond. This method will also overwrite the * current funding rate with the resolved funding rate returned by the Oracle if there has not been a more * recent published rate. Pending funding rates are unaffected by this method. * @dev This will revert if there is no price available for the disputed funding rate. This contract * will pull money from a PerpetualContract ONLY IF the dispute in question fails. * @param perpetual Contract to settle disputed funding rate for. * @param proposalTime Proposal time at which the disputed funding rate was proposed. */ function settleDispute(address perpetual, uint256 proposalTime) external nonReentrant() publishAndWithdrawProposal(perpetual) { FundingRateRecord storage fundingRateDispute = _getFundingRateDispute(perpetual, proposalTime); // Get the returned funding rate from the oracle. If this has not yet resolved will revert. // If the fundingRateDispute struct has been deleted, then this call will also fail because the proposal // time will be 0. FixedPoint.Signed memory settlementRate = _getOraclePrice(PerpetualInterface(perpetual).getFundingRateIdentifier(), proposalTime); // Dispute was successful if settled rate is different from proposed rate. bool disputeSucceeded = !settlementRate.isEqual(fundingRateDispute.proposal.rate); address proposer = disputeSucceeded ? fundingRateDispute.proposal.disputer : fundingRateDispute.proposal.proposer; emit DisputedRateSettled( perpetual, proposalTime, fundingRateDispute.proposal.proposer, fundingRateDispute.proposal.disputer, disputeSucceeded ); IERC20 collateralCurrency = IERC20(PerpetualInterface(perpetual).getCollateralCurrency()); // TODO: Decide whether loser of dispute should lose entire bond or partial if (disputeSucceeded) { // If dispute succeeds: // - Disputer earns back their bonds: dispute bond + final fee bond // - Disputer earns as reward: the proposal bond FixedPoint.Unsigned memory disputerRebate = fundingRateDispute.proposal.proposalBond.add(fundingRateDispute.proposal.finalFee); FixedPoint.Unsigned memory disputerReward = fundingRateDispute.proposal.proposalBond; collateralCurrency.safeTransfer(fundingRateDispute.proposal.disputer, disputerReward.add(disputerRebate).rawValue); } else { // If dispute fails: // - Proposer earns back their bonds: proposal bond + final fee bond // - Proposer earns as reward: the dispute bond FixedPoint.Unsigned memory proposerRebate = fundingRateDispute.proposal.proposalBond.add(fundingRateDispute.proposal.finalFee); FixedPoint.Unsigned memory proposerReward = fundingRateDispute.proposal.proposalBond; collateralCurrency.safeTransfer(fundingRateDispute.proposal.proposer, proposerReward.add(proposerRebate).rawValue); } // Update current rate to settlement rate if there has not been a published funding rate since the dispute // began. FundingRateRecord storage fundingRateRecord = _getFundingRateRecord(perpetual); if (fundingRateRecord.proposeTime <= proposalTime) { fundingRateRecord.rate = settlementRate; fundingRateRecord.proposeTime = proposalTime; // Note: Set rewards to 0 since we published the DVM resolved funding rate and there is no proposer to pay. emit PublishedRate(perpetual, settlementRate.rawValue, proposalTime, proposer, 0, 0, 0); } // Delete dispute delete fundingRateDisputes[perpetual][proposalTime]; } /** * @notice Publishes any expired pending proposals and pays out proposal rewards if neccessary. * @param perpetual Contract to check proposed funding rates for. */ function withdrawProposalRewards(address perpetual) external nonReentrant() publishAndWithdrawProposal(perpetual) {} /** * @notice Set the reward rate (per second) for a specific `perpetual` contract. * @dev Callable only by the Perpetual contract. */ function setRewardRate(address perpetual, FixedPoint.Unsigned memory rewardRate) external override nonReentrant() publishAndWithdrawProposal(perpetual) { require(msg.sender == perpetual, "Caller not perpetual"); FundingRateRecord storage fundingRateRecord = _getFundingRateRecord(perpetual); fundingRateRecord.rewardRatePerSecond = rewardRate; // Set last propose time to current time since rewards will start accruing from here on out. fundingRateRecord.proposeTime = getCurrentTime(); emit ChangedRewardRate(perpetual, rewardRate.rawValue); } /** * @notice Helpful method for proposers who want to calculate their potential rewards and useful for testing. */ function calculateProposalRewardPct( address perpetual, uint256 startTime, uint256 endTime, FixedPoint.Signed memory proposedRate, FixedPoint.Signed memory currentRate ) external view returns (FixedPoint.Unsigned memory reward) { return _calculateProposalRewardPct(perpetual, startTime, endTime, proposedRate, currentRate); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _publishRateAndWithdrawRewards(address perpetual) internal { FundingRateRecord storage fundingRateRecord = _getFundingRateRecord(perpetual); // Check if proposal liveness has expired if (_getProposalState(fundingRateRecord.proposal) != ProposalState.Expired) { return; } // Publish rate and proposal time. fundingRateRecord.rate = fundingRateRecord.proposal.rate; fundingRateRecord.proposeTime = fundingRateRecord.proposal.time; // Calculate reward for proposer using saved reward rate and current perpetual PfC. FixedPoint.Unsigned memory pfc = AdministrateeInterface(perpetual).pfc(); FixedPoint.Unsigned memory rewardRate = fundingRateRecord.proposal.rewardRate; FixedPoint.Unsigned memory reward = rewardRate.mul(pfc); // Pull reward payment from Perpetual, and transfer (payment + final fee bond + proposal bond) to proposer. // Note: Proposer always receives rebates for their bonds, but may not receive their proposer reward if the // perpetual fails to send fees. IERC20 collateralCurrency = IERC20(PerpetualInterface(perpetual).getCollateralCurrency()); FixedPoint.Unsigned memory amountToPay = fundingRateRecord.proposal.finalFee.add(fundingRateRecord.proposal.proposalBond); try PerpetualInterface(perpetual).withdrawFundingRateFees(reward) returns (FixedPoint.Unsigned memory rewardWithdrawn) { // Only transfer rewards if withdrawal from perpetual succeeded. amountToPay = amountToPay.add(rewardWithdrawn); } catch { // If the withdraw fails, then only rebate final fee and emit an alert. Because this method is called // by every other external method in the contract, its important that this method does not revert. emit WithdrawErrorIgnored(perpetual, reward.rawValue); reward = FixedPoint.fromUnscaledUint(0); } collateralCurrency.safeTransfer(fundingRateRecord.proposal.proposer, amountToPay.rawValue); emit PublishedRate( perpetual, fundingRateRecord.proposal.rate.rawValue, fundingRateRecord.proposal.time, fundingRateRecord.proposal.proposer, rewardRate.rawValue, reward.rawValue, amountToPay.rawValue ); // Delete proposal now that it has been published. delete fundingRateRecords[perpetual].proposal; } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(bytes32 identifier, uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(identifier, requestedTime); } // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. function _payFinalFees( IERC20 collateralCurrency, address payer, FixedPoint.Unsigned memory amount ) internal { if (amount.isEqual(0)) { return; } collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); emit FinalFeesPaid(address(collateralCurrency), amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _calculateProposalRewardPct( address perpetual, uint256 startTime, uint256 endTime, FixedPoint.Signed memory proposedRate, FixedPoint.Signed memory currentRate ) private view returns (FixedPoint.Unsigned memory reward) { uint256 timeDiff = endTime.sub(startTime); FixedPoint.Unsigned memory rewardRate = _getFundingRateRecord(perpetual).rewardRatePerSecond; // First compute the reward for the time elapsed. reward = rewardRate.mul(timeDiff); // Next scale the reward based on the absolute difference % between the current and proposed rates. // Formula: // - reward = reward * (1 + (proposedRate - currentRate) / currentRate) // Or, if currentRate = 0: // - reward = reward * (1 + (proposedRate - currentRate)) FixedPoint.Signed memory diffPercent = ( currentRate.isEqual(0) ? currentRate.sub(proposedRate) : currentRate.sub(proposedRate).div(currentRate) ); FixedPoint.Unsigned memory absDiffPercent = ( diffPercent.isLessThan(FixedPoint.fromUnscaledInt(0)) ? FixedPoint.fromSigned(diffPercent.mul(FixedPoint.fromUnscaledInt(-1))) : FixedPoint.fromSigned(diffPercent) ); // TODO: Set an arbitrary 200% ceiling on the value of `absDiffPercent` so this factor at most triples the reward: // - if (absDiffPercent > 2) then reward = reward * 3 // - else reward = reward * (1 + absDiffPercent) reward = reward.mul(absDiffPercent.isGreaterThan(2) ? FixedPoint.fromUnscaledUint(3) : absDiffPercent.add(1)); } // Returns the pending Proposal struct for a perpetual contract. function _getFundingRateRecord(address perpetual) private view returns (FundingRateRecord storage) { return fundingRateRecords[perpetual]; } // Returns the disputed Proposal struct for a perpetual and proposal time. This returns empty if the dispute // has already been resolved via `settleDispute`. function _getFundingRateDispute(address perpetual, uint256 time) private view returns (FundingRateRecord storage) { return fundingRateDisputes[perpetual][time]; } // Returns whether a proposal is a pending or expired proposal, or does not exist. function _getProposalState(Proposal storage proposal) private view returns (ProposalState) { uint256 time = proposal.time; if (time == 0) { return ProposalState.None; } else if (getCurrentTime() < time.add(proposalLiveness)) { return ProposalState.Pending; } else { return ProposalState.Expired; } } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(bytes32 identifier, uint256 requestedTime) internal view returns (FixedPoint.Signed memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(identifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(identifier, requestedTime); return FixedPoint.Signed(oraclePrice); } function _computeFinalFees(IERC20 collateralCurrency) internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } }
* @notice Gets the projected reward % for a successful proposer of a funding rate for a given perpetual contract. @dev This method is designed to be helpful for proposers in projecting their rewards. The reward % is a function of the perpetual contract's base reward % per second, the time elapsed since the last proposal, and the magnitude of change between the proposed and current funding rates. Note that unless the caller calls this method and proposes a funding rate in the same block, then the projected reward will be slightly underestimated. Note also that the actual reward is dependent on the perpetual's `PfC` at publish time and this method's reward %. @param perpetual Perpetual contract whose reward the caller is querying. @param rate Proposed rate. @return rewardRate Representing the reward % for a given contract if they were to propose a funding rate now./
function getRewardRateForContract(address perpetual, FixedPoint.Signed memory rate) external view nonReentrantView() returns (FixedPoint.Unsigned memory rewardRate) { FundingRateRecord storage fundingRateRecord = _getFundingRateRecord(perpetual); rewardRate = _calculateProposalRewardPct(perpetual, fundingRateRecord.proposeTime, getCurrentTime(), rate, fundingRateRecord.rate); }
12,587,714
[ 1, 3002, 326, 20939, 19890, 738, 364, 279, 6873, 450, 5607, 434, 279, 22058, 4993, 364, 279, 864, 1534, 6951, 1462, 6835, 18, 225, 1220, 707, 353, 26584, 358, 506, 28063, 364, 450, 917, 414, 316, 1984, 310, 3675, 283, 6397, 18, 1021, 19890, 738, 353, 279, 445, 434, 326, 1534, 6951, 1462, 6835, 1807, 1026, 19890, 738, 1534, 2205, 16, 326, 813, 9613, 3241, 326, 1142, 14708, 16, 471, 326, 13463, 434, 2549, 3086, 326, 20084, 471, 783, 22058, 17544, 18, 3609, 716, 3308, 326, 4894, 4097, 333, 707, 471, 450, 10522, 279, 22058, 4993, 316, 326, 1967, 1203, 16, 1508, 326, 20939, 19890, 903, 506, 21980, 3613, 395, 17275, 18, 3609, 2546, 716, 326, 3214, 19890, 353, 10460, 603, 326, 1534, 6951, 1462, 1807, 1375, 52, 74, 39, 68, 622, 3808, 813, 471, 333, 707, 1807, 19890, 12639, 225, 1534, 6951, 1462, 5722, 6951, 1462, 6835, 8272, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 4170, 359, 1060, 4727, 1290, 8924, 12, 2867, 1534, 6951, 1462, 16, 15038, 2148, 18, 12294, 3778, 4993, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1661, 426, 8230, 970, 1767, 1435, 203, 3639, 1135, 261, 7505, 2148, 18, 13290, 3778, 19890, 4727, 13, 203, 565, 288, 203, 3639, 478, 14351, 4727, 2115, 2502, 22058, 4727, 2115, 273, 389, 588, 42, 14351, 4727, 2115, 12, 457, 6951, 1462, 1769, 203, 203, 3639, 19890, 4727, 273, 389, 11162, 14592, 17631, 1060, 52, 299, 12, 457, 6951, 1462, 16, 22058, 4727, 2115, 18, 685, 4150, 950, 16, 5175, 950, 9334, 4993, 16, 22058, 4727, 2115, 18, 5141, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x182b43df8209dc4f7bdcd7942f59052646a827ad //Contract name: HumanTokenAllocator //Balance: 0.001 Ether //Verification Date: 4/27/2018 //Transacion Count: 27 // CODE STARTS HERE // Human token smart contract. // Developed by Phenom.Team <[email protected]> pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint a, uint b) internal constant returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } function div(uint a, uint b) internal constant returns(uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function sub(uint a, uint b) internal constant returns(uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal constant returns(uint) { uint c = a + b; assert(c >= a); return c; } } /** * @title ERC20 * @dev Standart ERC20 token interface */ contract ERC20 { uint public totalSupply = 0; mapping(address => uint) balances; mapping(address => mapping (address => uint)) allowed; function balanceOf(address _owner) constant returns (uint); function transfer(address _to, uint _value) returns (bool); function transferFrom(address _from, address _to, uint _value) returns (bool); function approve(address _spender, uint _value) returns (bool); function allowance(address _owner, address _spender) constant returns (uint); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * @title HumanTokenAllocator contract - issues Human tokens */ contract HumanTokenAllocator { using SafeMath for uint; HumanToken public Human; uint public rateEth = 700; // Rate USD per ETH uint public tokenPerUsdNumerator = 1; uint public tokenPerUsdDenominator = 1; uint public firstStageRaised; uint public secondStageRaised; uint public firstStageCap = 7*10**24; uint public secondStageCap = 32*10**24; uint public FIFTY_THOUSANDS_LIMIT = 5*10**22; uint teamPart = 7*10**24; bool public publicAllocationEnabled; address public teamFund; address public owner; address public oracle; // Oracle address address public company; event LogBuyForInvestor(address investor, uint humanValue, string txHash); event ControllerAdded(address _controller); event ControllerRemoved(address _controller); event FirstStageStarted(uint _timestamp); event SecondStageStarted(uint _timestamp); event AllocationFinished(uint _timestamp); event PublicAllocationEnabled(uint _timestamp); event PublicAllocationDisabled(uint _timestamp); mapping(address => bool) public isController; // Allows execution by the owner only modifier onlyOwner { require(msg.sender == owner); _; } // Allows execution by the oracle only modifier onlyOracle { require(msg.sender == oracle); _; } // Allows execution by the controllers only modifier onlyControllers { require(isController[msg.sender]); _; } // Possible statuses enum Status { Created, firstStage, secondStage, Finished } Status public status = Status.Created; /** * @dev Contract constructor function sets outside addresses */ function HumanTokenAllocator( address _owner, address _oracle, address _company, address _teamFund, address _eventManager ) public { owner = _owner; oracle = _oracle; company = _company; teamFund = _teamFund; Human = new HumanToken(address(this), _eventManager); } /** * @dev Fallback function calls buy(address _holder, uint _humanValue) function to issue tokens */ function() external payable { require(publicAllocationEnabled); uint humanValue = msg.value.mul(rateEth).mul(tokenPerUsdNumerator).div(tokenPerUsdDenominator); if (status == Status.secondStage) { require(humanValue >= FIFTY_THOUSANDS_LIMIT); } buy(msg.sender, humanValue); } /** * @dev Function to set rate of ETH * @param _rateEth current ETH rate */ function setRate(uint _rateEth) external onlyOracle { rateEth = _rateEth; } /** * @dev Function to set current token price * @param _numerator human token per usd numerator * @param _denominator human token per usd denominator */ function setPrice(uint _numerator, uint _denominator) external onlyOracle { tokenPerUsdNumerator = _numerator; tokenPerUsdDenominator = _denominator; } /** * @dev Function to issues tokens for investors who made purchases in other cryptocurrencies * @param _holder address the tokens will be issued to * @param _humanValue number of Human tokens * @param _txHash transaction hash of investor's payment */ function buyForInvestor( address _holder, uint _humanValue, string _txHash ) external onlyControllers { buy(_holder, _humanValue); LogBuyForInvestor(_holder, _humanValue, _txHash); } /** * @dev Function to issue tokens for investors who paid in ether * @param _holder address which the tokens will be issued tokens * @param _humanValue number of Human tokens */ function buy(address _holder, uint _humanValue) internal { require(status == Status.firstStage || status == Status.secondStage); if (status == Status.firstStage) { require(firstStageRaised + _humanValue <= firstStageCap); firstStageRaised = firstStageRaised.add(_humanValue); } else { require(secondStageRaised + _humanValue <= secondStageCap); secondStageRaised = secondStageRaised.add(_humanValue); } Human.mintTokens(_holder, _humanValue); } /** * @dev Function to add an address to the controllers * @param _controller an address that will be added to managers list */ function addController(address _controller) onlyOwner external { require(!isController[_controller]); isController[_controller] = true; ControllerAdded(_controller); } /** * @dev Function to remove an address to the controllers * @param _controller an address that will be removed from managers list */ function removeController(address _controller) onlyOwner external { require(isController[_controller]); isController[_controller] = false; ControllerRemoved(_controller); } /** * @dev Function to start the first stage of human token allocation * and to issue human token for team fund */ function startFirstStage() public onlyOwner { require(status == Status.Created); Human.mintTokens(teamFund, teamPart); status = Status.firstStage; FirstStageStarted(now); } /** * @dev Function to start the second stage of human token allocation */ function startSecondStage() public onlyOwner { require(status == Status.firstStage); status = Status.secondStage; SecondStageStarted(now); } /** * @dev Function to finish human token allocation and to finish token issue */ function finish() public onlyOwner { require (status == Status.secondStage); status = Status.Finished; AllocationFinished(now); } /** * @dev Function to enable public token allocation */ function enable() public onlyOwner { publicAllocationEnabled = true; PublicAllocationEnabled(now); } /** * @dev Function to disable public token allocation */ function disable() public onlyOwner { publicAllocationEnabled = false; PublicAllocationDisabled(now); } /** * @dev Function to withdraw ether */ function withdraw() external onlyOwner { company.transfer(address(this).balance); } /** * @dev Allows owner to transfer out any accidentally sent ERC20 tokens * @param tokenAddress token address * @param tokens transfer amount */ function transferAnyTokens(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20(tokenAddress).transfer(owner, tokens); } } /** * @title HumanToken * @dev Human token smart-contract */ contract HumanToken is ERC20 { using SafeMath for uint; string public name = "Human"; string public symbol = "Human"; uint public decimals = 18; uint public voteCost = 10**18; // Owner address address public owner; address public eventManager; mapping (address => bool) isActiveEvent; //events event EventAdded(address _event); event Contribute(address _event, address _contributor, uint _amount); event Vote(address _event, address _contributor, bool _proposal); // Allows execution by the contract owner only modifier onlyOwner { require(msg.sender == owner); _; } // Allows execution by the event manager only modifier onlyEventManager { require(msg.sender == eventManager); _; } // Allows contributing and voting only to human events modifier onlyActive(address _event) { require(isActiveEvent[_event]); _; } /** * @dev Contract constructor function sets owner address * @param _owner owner address */ function HumanToken(address _owner, address _eventManager) public { owner = _owner; eventManager = _eventManager; } /** * @dev Function to add a new event from TheHuman team * @param _event a new event address */ function addEvent(address _event) external onlyEventManager { require (!isActiveEvent[_event]); isActiveEvent[_event] = true; EventAdded(_event); } /** * @dev Function to change vote cost, by default vote cost equals 1 Human token * @param _voteCost a new vote cost */ function setVoteCost(uint _voteCost) external onlyEventManager { voteCost = _voteCost; } /** * @dev Function to donate for event * @param _event address of event * @param _amount donation amount */ function donate(address _event, uint _amount) public onlyActive(_event) { require (transfer(_event, _amount)); require (HumanEvent(_event).contribute(msg.sender, _amount)); Contribute(_event, msg.sender, _amount); } /** * @dev Function voting for the success of the event * @param _event address of event * @param _proposal true - event completed successfully, false - otherwise */ function vote(address _event, bool _proposal) public onlyActive(_event) { require(transfer(_event, voteCost)); require(HumanEvent(_event).vote(msg.sender, _proposal)); Vote(_event, msg.sender, _proposal); } /** * @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) external onlyOwner { require(_value > 0); balances[_holder] = balances[_holder].add(_value); totalSupply = totalSupply.add(_value); Transfer(0x0, _holder, _value); } /** * @dev Get balance of tokens holder * @param _holder holder's address * @return balance of investor */ function balanceOf(address _holder) constant 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) { balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); 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) { balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); 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; 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) constant returns (uint) { return allowed[_owner][_spender]; } /** * @dev Allows owner to transfer out any accidentally sent ERC20 tokens * @param tokenAddress token address * @param tokens transfer amount */ function transferAnyTokens(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20(tokenAddress).transfer(owner, tokens); } } contract HumanEvent { using SafeMath for uint; uint public totalRaised; uint public softCap; uint public positiveVotes; uint public negativeVotes; address public alternative; address public owner; HumanToken public human; mapping (address => uint) public contributions; mapping (address => bool) public voted; mapping (address => bool) public claimed; // Allows execution by the contract owner only modifier onlyOwner { require(msg.sender == owner); _; } // Allows execution by the contract owner only modifier onlyHuman { require(msg.sender == address(human)); _; } // Possible Event statuses enum StatusEvent { Created, Fundraising, Failed, Evaluating, Voting, Finished } StatusEvent public statusEvent = StatusEvent.Created; function HumanEvent( address _owner, uint _softCap, address _alternative, address _human ) public { owner = _owner; softCap = _softCap; alternative = _alternative; human = HumanToken(_human); } function startFundraising() public onlyOwner { require(statusEvent == StatusEvent.Created); statusEvent = StatusEvent.Fundraising; } function startEvaluating() public onlyOwner { require(statusEvent == StatusEvent.Fundraising); if (totalRaised >= softCap) { statusEvent = StatusEvent.Evaluating; } else { statusEvent = StatusEvent.Failed; } } function startVoting() public onlyOwner { require(statusEvent == StatusEvent.Evaluating); statusEvent = StatusEvent.Voting; } function finish() public onlyOwner { require(statusEvent == StatusEvent.Voting); if (positiveVotes >= negativeVotes) { statusEvent = StatusEvent.Finished; } else { statusEvent = StatusEvent.Failed; } } function claim() public { require(!claimed[msg.sender]); claimed[msg.sender] = true; uint contribution; if (statusEvent == StatusEvent.Failed) { contribution = contribution.add(contributions[msg.sender]); contributions[msg.sender] = 0; } if(voted[msg.sender] && statusEvent != StatusEvent.Voting) { uint _voteCost = human.voteCost(); contribution = contribution.add(_voteCost); } require(contribution > 0); require(human.transfer(msg.sender, contribution)); } function vote(address _voter, bool _proposal) external onlyHuman returns (bool) { require(!voted[_voter] && statusEvent == StatusEvent.Voting); voted[_voter] = true; if (_proposal) { positiveVotes++; } else { negativeVotes++; } return true; } function contribute(address _contributor, uint _amount) external onlyHuman returns(bool) { require (statusEvent == StatusEvent.Fundraising); contributions[_contributor] = contributions[_contributor].add(_amount); totalRaised = totalRaised.add(_amount); return true; } function withdraw() external onlyOwner { require (statusEvent == StatusEvent.Finished); require (human.transfer(alternative, totalRaised)); } }
* @title HumanTokenAllocator contract - issues Human tokens/ Allows execution by the owner only
contract HumanTokenAllocator { using SafeMath for uint; HumanToken public Human; uint public tokenPerUsdNumerator = 1; uint public tokenPerUsdDenominator = 1; uint public firstStageRaised; uint public secondStageRaised; uint public firstStageCap = 7*10**24; uint public secondStageCap = 32*10**24; uint public FIFTY_THOUSANDS_LIMIT = 5*10**22; uint teamPart = 7*10**24; bool public publicAllocationEnabled; address public teamFund; address public owner; address public company; event LogBuyForInvestor(address investor, uint humanValue, string txHash); event ControllerAdded(address _controller); event ControllerRemoved(address _controller); event FirstStageStarted(uint _timestamp); event SecondStageStarted(uint _timestamp); event AllocationFinished(uint _timestamp); event PublicAllocationEnabled(uint _timestamp); event PublicAllocationDisabled(uint _timestamp); mapping(address => bool) public isController; modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyOracle { require(msg.sender == oracle); _; } modifier onlyControllers { require(isController[msg.sender]); _; } enum Status { Created, firstStage, secondStage, Finished } Status public status = Status.Created; function HumanTokenAllocator( address _owner, address _oracle, address _company, address _teamFund, address _eventManager ) public { owner = _owner; oracle = _oracle; company = _company; teamFund = _teamFund; Human = new HumanToken(address(this), _eventManager); } function() external payable { require(publicAllocationEnabled); uint humanValue = msg.value.mul(rateEth).mul(tokenPerUsdNumerator).div(tokenPerUsdDenominator); if (status == Status.secondStage) { require(humanValue >= FIFTY_THOUSANDS_LIMIT); } buy(msg.sender, humanValue); } function() external payable { require(publicAllocationEnabled); uint humanValue = msg.value.mul(rateEth).mul(tokenPerUsdNumerator).div(tokenPerUsdDenominator); if (status == Status.secondStage) { require(humanValue >= FIFTY_THOUSANDS_LIMIT); } buy(msg.sender, humanValue); } function setRate(uint _rateEth) external onlyOracle { rateEth = _rateEth; } function setPrice(uint _numerator, uint _denominator) external onlyOracle { tokenPerUsdNumerator = _numerator; tokenPerUsdDenominator = _denominator; } function buyForInvestor( address _holder, uint _humanValue, string _txHash ) external onlyControllers { buy(_holder, _humanValue); LogBuyForInvestor(_holder, _humanValue, _txHash); } function buy(address _holder, uint _humanValue) internal { require(status == Status.firstStage || status == Status.secondStage); if (status == Status.firstStage) { require(firstStageRaised + _humanValue <= firstStageCap); firstStageRaised = firstStageRaised.add(_humanValue); require(secondStageRaised + _humanValue <= secondStageCap); secondStageRaised = secondStageRaised.add(_humanValue); } Human.mintTokens(_holder, _humanValue); } function buy(address _holder, uint _humanValue) internal { require(status == Status.firstStage || status == Status.secondStage); if (status == Status.firstStage) { require(firstStageRaised + _humanValue <= firstStageCap); firstStageRaised = firstStageRaised.add(_humanValue); require(secondStageRaised + _humanValue <= secondStageCap); secondStageRaised = secondStageRaised.add(_humanValue); } Human.mintTokens(_holder, _humanValue); } } else { function addController(address _controller) onlyOwner external { require(!isController[_controller]); isController[_controller] = true; ControllerAdded(_controller); } function removeController(address _controller) onlyOwner external { require(isController[_controller]); isController[_controller] = false; ControllerRemoved(_controller); } function startFirstStage() public onlyOwner { require(status == Status.Created); Human.mintTokens(teamFund, teamPart); status = Status.firstStage; FirstStageStarted(now); } function startSecondStage() public onlyOwner { require(status == Status.firstStage); status = Status.secondStage; SecondStageStarted(now); } function finish() public onlyOwner { require (status == Status.secondStage); status = Status.Finished; AllocationFinished(now); } function enable() public onlyOwner { publicAllocationEnabled = true; PublicAllocationEnabled(now); } function disable() public onlyOwner { publicAllocationEnabled = false; PublicAllocationDisabled(now); } function withdraw() external onlyOwner { company.transfer(address(this).balance); } function transferAnyTokens(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20(tokenAddress).transfer(owner, tokens); } }
6,396,336
[ 1, 28201, 1345, 21156, 6835, 225, 300, 225, 8296, 670, 6925, 2430, 19, 25619, 4588, 635, 326, 3410, 1338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 670, 6925, 1345, 21156, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 565, 670, 6925, 1345, 1071, 670, 6925, 31, 203, 565, 2254, 1071, 1147, 2173, 3477, 72, 2578, 7385, 273, 404, 31, 203, 565, 2254, 1071, 1147, 2173, 3477, 72, 8517, 26721, 273, 404, 31, 203, 565, 2254, 1071, 1122, 8755, 12649, 5918, 31, 203, 565, 2254, 1071, 2205, 8755, 12649, 5918, 31, 203, 565, 2254, 1071, 1122, 8755, 4664, 273, 2371, 14, 2163, 636, 3247, 31, 203, 565, 2254, 1071, 2205, 8755, 4664, 273, 3847, 14, 2163, 636, 3247, 31, 203, 565, 2254, 1071, 4011, 4464, 61, 67, 2455, 21667, 1258, 3948, 67, 8283, 273, 1381, 14, 2163, 636, 3787, 31, 203, 565, 2254, 5927, 1988, 273, 2371, 14, 2163, 636, 3247, 31, 203, 203, 565, 1426, 1071, 1071, 17353, 1526, 31, 203, 203, 565, 1758, 1071, 5927, 42, 1074, 31, 203, 565, 1758, 1071, 3410, 31, 203, 565, 1758, 1071, 9395, 31, 203, 203, 565, 871, 1827, 38, 9835, 1290, 3605, 395, 280, 12, 2867, 2198, 395, 280, 16, 2254, 8672, 620, 16, 533, 2229, 2310, 1769, 203, 565, 871, 6629, 8602, 12, 2867, 389, 5723, 1769, 203, 565, 871, 6629, 10026, 12, 2867, 389, 5723, 1769, 203, 565, 871, 5783, 8755, 9217, 12, 11890, 389, 5508, 1769, 203, 565, 871, 7631, 8755, 9217, 12, 11890, 389, 5508, 1769, 203, 565, 871, 24242, 10577, 12, 11890, 389, 5508, 1769, 203, 565, 871, 7224, 17353, 1526, 12, 11890, 389, 5508, 1769, 203, 565, 871, 7224, 17353, 8853, 12, 11890, 2 ]
./full_match/4/0x087c1E153cb008471fAb7AA8AF2f8226D8b15093/sources/browser/Untitled.sol
* @notice Returns the current per-block borrow interest rate for this cToken @return The borrow interest rate per block, scaled by 1e18/
function borrowRatePerBlock() external view returns (uint) { (uint opaqueErr, uint borrowRateMantissa) = interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); return borrowRateMantissa; }
793,068
[ 1, 1356, 326, 783, 1534, 17, 2629, 29759, 16513, 4993, 364, 333, 276, 1345, 327, 1021, 29759, 16513, 4993, 1534, 1203, 16, 12304, 635, 404, 73, 2643, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 29759, 4727, 2173, 1768, 1435, 3903, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 261, 11890, 22519, 2524, 16, 2254, 29759, 4727, 49, 970, 21269, 13, 273, 16513, 4727, 1488, 18, 588, 38, 15318, 4727, 12, 588, 39, 961, 25355, 9334, 2078, 38, 280, 3870, 16, 2078, 607, 264, 3324, 1769, 203, 3639, 327, 29759, 4727, 49, 970, 21269, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x0F265cA07bBdF16700ae7E1C7e1efD04f6e22718/sources/_connext/smart-contracts/contracts/core/connext/libraries/TokenId.sol
Tokens are identified by a TokenId: domain - 4 byte chain ID of the chain from which the token originates id - 32 byte identifier of the token address on the origin chain, in that chain's address format
struct TokenId { uint32 domain; bytes32 id; pragma solidity 0.8.17; }
11,604,042
[ 1, 5157, 854, 9283, 635, 279, 3155, 548, 30, 2461, 300, 1059, 1160, 2687, 1599, 434, 326, 2687, 628, 1492, 326, 1147, 4026, 815, 612, 300, 3847, 1160, 2756, 434, 326, 1147, 1758, 603, 326, 4026, 2687, 16, 316, 716, 2687, 1807, 1758, 740, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1697, 3155, 548, 288, 203, 225, 2254, 1578, 2461, 31, 203, 225, 1731, 1578, 612, 31, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 4033, 31, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * Copyright (C) 2018 Smartz, 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). */ pragma solidity ^0.4.18; import "zeppelin-solidity/contracts/token/ERC20Basic.sol"; /** * @title SwapTokenForToken * Swap tokens of participant1 for tokens of participant2 * * @author Vladimir Khramov <[email protected]> */ contract SwapTokenForToken { address public participant1; address public participant2; ERC20Basic public participant1Token; uint256 public participant1TokensCount; ERC20Basic public participant2Token; uint256 public participant2TokensCount; bool public isFinished = false; /** * Constructor */ function SwapTokenForToken( address _participant1, address _participant1TokenAddress, uint256 _participant1TokensCount, address _participant2, address _participant2TokenAddress, uint256 _participant2TokensCount ) public { require(_participant1 != _participant2); require(_participant1TokenAddress != _participant2TokenAddress); require(_participant1TokenAddress != address(0)); require(_participant2TokenAddress != address(0)); require(_participant1TokensCount > 0); require(_participant2TokensCount > 0); participant1 = _participant1; participant2 = _participant2; participant1Token = ERC20Basic(_participant1TokenAddress); participant1TokensCount = _participant1TokensCount; participant2Token = ERC20Basic(_participant2TokenAddress); participant2TokensCount = _participant2TokensCount; } /** * No direct payments */ function() external { revert(); } /** * Swap tokens for tokens */ function swap() external { require(!isFinished); uint256 tokens1Balance = participant1Token.balanceOf(this); require(tokens1Balance >= participant1TokensCount); uint256 tokens2Balance = participant2Token.balanceOf(this); require(tokens2Balance >= participant2TokensCount); isFinished = true; //check transfer uint token1Participant2InitialBalance = participant1Token.balanceOf(participant2); uint token2Participant1InitialBalance = participant2Token.balanceOf(participant1); require(participant1Token.transfer(participant2, participant1TokensCount)); if (tokens1Balance > participant1TokensCount) { require( participant1Token.transfer(participant1, tokens1Balance - participant1TokensCount) ); } require(participant2Token.transfer(participant1, participant2TokensCount)); if (tokens2Balance > participant2TokensCount) { require( participant2Token.transfer(participant2, tokens2Balance - participant2TokensCount) ); } //check transfer assert(participant1Token.balanceOf(participant2) >= token1Participant2InitialBalance+participant1TokensCount); assert(participant2Token.balanceOf(participant1) >= token2Participant1InitialBalance+participant2TokensCount); } /** * Refund tokens by participants */ function refund() external { if (msg.sender == participant1) { uint256 tokens1Balance = participant1Token.balanceOf(this); require(tokens1Balance > 0); participant1Token.transfer(participant1, tokens1Balance); } else if (msg.sender == participant2) { uint256 tokens2Balance = participant2Token.balanceOf(this); require(tokens2Balance > 0); participant2Token.transfer(participant2, tokens2Balance); } else { revert(); } } /** * Tokens count sent by participant #1 */ function participant1SentTokensCount() public view returns (uint256) { return participant1Token.balanceOf(this); } /** * Tokens count sent by participant #2 */ function participant2SentTokensCount() public view returns (uint256) { return participant2Token.balanceOf(this); } }
* Tokens count sent by participant #2/
function participant2SentTokensCount() public view returns (uint256) { return participant2Token.balanceOf(this); }
13,046,497
[ 1, 5157, 1056, 3271, 635, 14188, 576, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 14188, 22, 7828, 5157, 1380, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 14188, 22, 1345, 18, 12296, 951, 12, 2211, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.0; import './ConsensusMachine.sol'; contract AddressManager is ConsensusMachine {/// Change the Gavels Agent Address address public GavelTokenAddress; address public RedPenTokenAddress; address public GoldStarAddress; address public PinkSlipAddress; address public ChadBadgeAddress; address public ColoredIDAddress; address public JuryPoolAddress; address public CourtClerk; address public GavelDAOAgent; address public JuryDAOAgent; address public TreasuryAddress; address public TheCourtAddress; address public MiniBailiff; address public newAddressManager; // For the ability to upgrade if neccesary. bool public hasMovedToNewAddress = false; string private errorMessage = "the hell are you doing? C'mon"; string private zeroAddressWarning = "C'mon"; string public frontEnd = "content hash stored @ coloredbadges.eth"; uint public badgeCount = 0; event AddressUpdated(address, string); constructor(address juryDAOAgent, address gavelDAOAgent, address treasuryAddress, address theCourtAddress, address _MiniBailiff) ConsensusMachine(juryDAOAgent, gavelDAOAgent, theCourtAddress) { GavelDAOAgent = gavelDAOAgent; JuryDAOAgent = juryDAOAgent; TreasuryAddress = treasuryAddress; TheCourtAddress = theCourtAddress; MiniBailiff = _MiniBailiff; } ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// /// @dev //// /// Address Setters //// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// function setnewAddressManager(address newAddressManagerAddress) public THE_COURT BAILIFF { require(newAddressManagerAddress != address(0), errorMessage); newAddressManager = newAddressManagerAddress; hasMovedToNewAddress = true; _resetVote(); emit AddressUpdated(newAddressManagerAddress, "New AddressManagerAddress"); } function _setAgent( bytes32 ROLE , address newAgentAddress) internal returns (bool) { require(newAgentAddress != address(0), errorMessage); require(!hasRole(ROLE, newAgentAddress)); grantRole(ROLE, newAgentAddress); emit AddressUpdated(newAgentAddress, "Check Role Events" ); return true; } /// Change the Gavel Agent Address function addGavelAgent(address newAgentAddress) public GAVELS { bool success = _setAgent(GAVELS_BAILIFF, newAgentAddress); require(success == true); emit AddressUpdated(newAgentAddress, "New Gavel Agent"); } /// Change the Jury Agent Address function addJuryAgent(address newAgentAddress) public GAVELS { bool success = _setAgent(JURY_BAILIFF, newAgentAddress); require(success == true); emit AddressUpdated(newAgentAddress, "New Jury Agent"); } function addMiniBailiff(address newAgentAddress) public BAILIFF { bool success = _setAgent(MINI_BAILIFF_ROLE, newAgentAddress); require(success == true); emit AddressUpdated(newAgentAddress, "New Mini Bailiff"); } /// Change the Court Agent Address function setTheCourtAgent(address newAgentAddress) public GAVELS { bool success = _setAgent(THE_COURT_ROLE, newAgentAddress); require(success == true); emit AddressUpdated(newAgentAddress, "New Court Elected"); } /// Change the Treasury Address function setTreasuryAddress(address newTreasuryAddress) public THE_COURT { require(newTreasuryAddress != address(0), errorMessage); TreasuryAddress = newTreasuryAddress; _resetVote(); emit AddressUpdated(newTreasuryAddress, "New Treasury Address"); } function setCourtAddress(address newCourtAddress) public THE_COURT { require(newCourtAddress != address(0), zeroAddressWarning); TheCourtAddress = newCourtAddress; _resetVote(); emit AddressUpdated(newCourtAddress, "New Court Address"); } function setCourtClerk(address _newCourtClerkAddress) public BAILIFF { require(_newCourtClerkAddress != address(0), zeroAddressWarning); CourtClerk = _newCourtClerkAddress; emit AddressUpdated(CourtClerk, "New Court Clerk"); } function setGavelTokenAddress(address newGavelTokenAddress) public GAVELS { require(newGavelTokenAddress != address(0), zeroAddressWarning); require(newGavelTokenAddress != RedPenTokenAddress, "Don't mess with the balance of power"); GavelTokenAddress = newGavelTokenAddress; emit AddressUpdated(newGavelTokenAddress, "New Gavel Token Address"); } function setJuryPoolAddress(address newJuryPoolAddress) public JURY { require(newJuryPoolAddress != address(0), zeroAddressWarning); require(newJuryPoolAddress != GavelTokenAddress, "Don't mess with the balance of power"); JuryPoolAddress = newJuryPoolAddress; emit AddressUpdated(newJuryPoolAddress, "New Jury Pool Address"); } function setRedPenTokenAddress(address newRedPenTokenAddress) public JURY { require(newRedPenTokenAddress != address(0), zeroAddressWarning); require(newRedPenTokenAddress != GavelTokenAddress, "Don't mess with the balance of power"); RedPenTokenAddress = newRedPenTokenAddress; emit AddressUpdated(newRedPenTokenAddress, "New Red Pen Token Address"); } function setGoldStarAddress(address newGoldStarAddress) public THE_COURT { require(newGoldStarAddress != address(0), zeroAddressWarning); require(newGoldStarAddress != GavelTokenAddress && newGoldStarAddress != RedPenTokenAddress, "What are you doing?"); GoldStarAddress = newGoldStarAddress; _resetVote(); emit AddressUpdated(newGoldStarAddress, "New Gold Star Address"); } function setPinkSlipAddress(address newPinkSlipAddress) public THE_COURT { require(newPinkSlipAddress != address(0), zeroAddressWarning); require(newPinkSlipAddress != GavelTokenAddress && newPinkSlipAddress != RedPenTokenAddress, "What are you doing?"); PinkSlipAddress = newPinkSlipAddress; _resetVote(); emit AddressUpdated(newPinkSlipAddress, "New PinkSlip Address"); } function setChadBadgeAddress(address newChadBadgeAddress) public THE_COURT { require(newChadBadgeAddress != address(0), zeroAddressWarning); require(newChadBadgeAddress != GavelTokenAddress && newChadBadgeAddress != RedPenTokenAddress, "What are you doing?"); ChadBadgeAddress = newChadBadgeAddress; _resetVote(); emit AddressUpdated(newChadBadgeAddress, "New ChadBadge Address"); } function setColoredIDAddress(address newColoredIDAddress) public THE_COURT { require(newColoredIDAddress != address(0), zeroAddressWarning); require(newColoredIDAddress != GavelTokenAddress && newColoredIDAddress != RedPenTokenAddress, "What are you doing?"); ColoredIDAddress = newColoredIDAddress; _resetVote(); emit AddressUpdated(newColoredIDAddress, "New ColoredID Address"); } ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// /// @dev END //// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// } ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// /// @dev //// /// @dev //// /// @dev //// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// /// @dev //// /// @dev //// ///////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////
Change the Jury Agent Address
function addJuryAgent(address newAgentAddress) public GAVELS { bool success = _setAgent(JURY_BAILIFF, newAgentAddress); require(success == true); emit AddressUpdated(newAgentAddress, "New Jury Agent"); }
967,252
[ 1, 3043, 326, 804, 22498, 8669, 5267, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 527, 46, 22498, 3630, 12, 2867, 394, 3630, 1887, 13, 1071, 611, 5856, 2247, 55, 288, 203, 5411, 1426, 2216, 273, 389, 542, 3630, 12, 46, 1099, 61, 67, 12536, 45, 2053, 2246, 16, 394, 3630, 1887, 1769, 203, 5411, 2583, 12, 4768, 422, 638, 1769, 203, 5411, 3626, 5267, 7381, 12, 2704, 3630, 1887, 16, 315, 1908, 804, 22498, 8669, 8863, 203, 203, 3639, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x80832720Dde0a4B3176125Fd80CAcDFd29851217/sources/ADZbuzzCommunityToken.sol
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract ADZbuzzCommunityToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function ADZbuzzCommunityToken() public { symbol = "ACT81816"; name = "ADZbuzz Wholesomeinspiration.com Community Token"; decimals = 8; _totalSupply = 200000000000000; balances[0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187] = _totalSupply; emit Transfer(address(0), 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
4,175,412
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6835, 11738, 62, 70, 9510, 12136, 13352, 1345, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 3639, 533, 1071, 3273, 31, 203, 3639, 533, 1071, 225, 508, 31, 203, 3639, 2254, 28, 1071, 15105, 31, 203, 3639, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 377, 203, 3639, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 3639, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 377, 203, 377, 203, 3639, 445, 11738, 62, 70, 9510, 12136, 13352, 1345, 1435, 1071, 288, 203, 5411, 3273, 273, 315, 6526, 28, 2643, 2313, 14432, 203, 5411, 508, 273, 315, 1880, 62, 70, 9510, 3497, 9112, 1742, 267, 1752, 5447, 18, 832, 16854, 13352, 3155, 14432, 203, 5411, 15105, 273, 1725, 31, 203, 5411, 389, 4963, 3088, 1283, 273, 576, 12648, 9449, 31, 203, 5411, 324, 26488, 63, 20, 92, 23, 74, 7301, 71, 20, 38, 3103, 28, 7235, 71, 5718, 30042, 39, 22, 39, 29, 3103, 7228, 3030, 29, 9988, 20, 69, 28, 69, 28, 69, 2643, 27, 65, 273, 389, 4963, 3088, 1283, 31, 203, 5411, 3626, 12279, 12, 2867, 12, 20, 3631, 374, 92, 23, 74, 7301, 71, 20, 38, 3103, 28, 7235, 71, 5718, 30042, 39, 22, 39, 29, 3103, 7228, 3030, 29, 9988, 20, 69, 28, 69, 28, 69, 2643, 27, 16, 389, 4963, 3088, 1283, 1769, 203, 3639, 289, 203, 377, 203, 377, 203, 3639, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 5411, 2 ]
pragma solidity ^0.5.8; contract Ownable { address public owner; constructor () public{ owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner, "Votante no autorizado."); _; } } contract Voting is Ownable { // Candidates map uint8 private candidatesListCounter = 0; uint8[9] private cantidateListId; bytes32[9] private cantidateListName; uint8[9] private candidateListVotes; // Candidates utilities mapping(bytes32 => bool) private candidateValidator; // Voters map uint8[28] private votersListId; bytes32[28] private votersListIdentification; bytes32[28] private votersListName; // Voters utilities mapping(bytes32 => address) private votersListAddressMap; mapping(bytes32 => uint8) private votersListValidator; mapping(bytes32 => bool) private votersListVoted; mapping(address => uint8) private votersListIdMap; // Voting starter and finisher bool votingIsOpen; // Events event AddedCandidate(bytes32 candidateStored); event AddedVote(bytes32 candidateName, uint8 candidateVotes); /** * Constructor. Initialize the voters. */ constructor(uint8[28] memory _votersListId, bytes32[28] memory _votersListIdentification, bytes32[28] memory _votersListName, uint8[9] memory _cantidateListId, bytes32[9] memory _cantidateListName) public { // Voters initialization votersListId = _votersListId; votersListIdentification = _votersListIdentification; votersListName = _votersListName; for( uint8 i = 0 ; i < 28; i++){ votersListValidator[votersListIdentification[i]] = 1; } // Candidates initialization cantidateListId = _cantidateListId; cantidateListName = _cantidateListName; for( uint8 i = 0 ; i < 9; i++){ candidateListVotes[i] = 0; } } modifier onlyNewCandidate(bytes32 _candidate){ require(candidateValidator[_candidate] != true, "Candidato solo puede ser añadido una sola vez."); _; } modifier onlyValidVoter(bytes32 _voterIdentification){ require(votersListValidator[_voterIdentification] == 1, "Votante solo puede ser verificado una sola vez."); _; } function getCandidates() external view returns(uint8[9] memory, bytes32[9] memory) { return (cantidateListId, cantidateListName); } function getCandidateVotes(uint8 _candidateId) external view returns(uint8) { require(votingIsOpen == false, "Solo se pueden ver los votos cuando la votación esté cerrada."); return candidateListVotes[_candidateId]; } function getCandidatesVotes() external view returns(bytes32[9] memory, uint8[9] memory) { require(votingIsOpen == false, "Solo se pueden ver los votos cuando la votación esté cerrada."); return (cantidateListName, candidateListVotes); } function associateUserToAddress(bytes32 _voterIdentification) external onlyValidVoter(_voterIdentification) returns(address, bytes32) { votersListAddressMap[_voterIdentification] = msg.sender; votersListValidator[_voterIdentification] = 2; return (msg.sender, _voterIdentification); } function addCandidate(bytes32 _candidate) internal onlyOwner onlyNewCandidate(_candidate) { // Storing candidate cantidateListId[candidatesListCounter] = candidatesListCounter; cantidateListName[candidatesListCounter] = _candidate; candidateListVotes[candidatesListCounter] = 0; // Adding the validator to true for next try candidateValidator[_candidate] = true; // Adds a new list counter for the next candidate candidatesListCounter = candidatesListCounter + 1; emit AddedCandidate(_candidate); } function vote(uint8 _candidateId, bytes32 _voterIdentification) external { // Validadtions require(votingIsOpen == true, "Solo se puede votar cuando el tiempo de votación este activo."); require(votersListAddressMap[_voterIdentification] == msg.sender, "El votante solo puede votar usando una el address que validó."); require(votersListValidator[_voterIdentification] == 2, "Votante debe haber sido validado."); require(votersListVoted[_voterIdentification] == false, "Votante solo puede votar una vez."); // Incrementing voting count uint8 _candidateCount = candidateListVotes[_candidateId] + 1; // Removing the possibility for this voter to vote again votersListVoted[_voterIdentification] = true; votersListValidator[_voterIdentification] = 3; // Asigning the new votes to the candidate candidateListVotes[_candidateId] = _candidateCount; emit AddedVote(cantidateListName[_candidateId], _candidateCount); } function initializeVoting() external onlyOwner { votingIsOpen = true; } function finishVoting() external onlyOwner { votingIsOpen = false; } function getVotingStatus() external view returns(bool) { return votingIsOpen; } function() external payable {} }
Candidates initialization
cantidateListId = _cantidateListId;
6,411,058
[ 1, 18455, 10313, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 848, 18081, 340, 682, 548, 273, 389, 71, 970, 350, 340, 682, 548, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts/ErrorReporter.sol pragma solidity 0.4.24; contract ErrorReporter { /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. */ event Failure(uint256 error, uint256 info, uint256 detail); enum Error { NO_ERROR, OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event UNAUTHORIZED, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, DIVISION_BY_ZERO, BAD_INPUT, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_TRANSFER_FAILED, MARKET_NOT_SUPPORTED, SUPPLY_RATE_CALCULATION_FAILED, BORROW_RATE_CALCULATION_FAILED, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_OUT_FAILED, INSUFFICIENT_LIQUIDITY, INSUFFICIENT_BALANCE, INVALID_COLLATERAL_RATIO, MISSING_ASSET_PRICE, EQUITY_INSUFFICIENT_BALANCE, INVALID_CLOSE_AMOUNT_REQUESTED, ASSET_NOT_PRICED, INVALID_LIQUIDATION_DISCOUNT, INVALID_COMBINED_RISK_PARAMETERS, ZERO_ORACLE_ADDRESS, CONTRACT_PAUSED, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, ETHER_AMOUNT_MISMATCH_ERROR } /** * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_CONTRACT_PAUSED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_CONTRACT_PAUSED, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_FETCH_ASSET_PRICE_FAILED, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTRACT_PAUSED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_CONTRACT_PAUSED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_FETCH_PRICE_FAILED, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_CONTRACT_PAUSED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, SEND_ETHER_ADMIN_CHECK_FAILED, ETHER_AMOUNT_MISMATCH_ERROR } /** * @dev use this when reporting a known error from the Alkemi Earn Verified or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(FailureInfo info, uint256 opaqueError) internal returns (uint256) { emit Failure(uint256(Error.OPAQUE_ERROR), uint256(info), opaqueError); return uint256(Error.OPAQUE_ERROR); } } // File: contracts/CarefulMath.sol // Cloned from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol -> Commit id: 24a0bc2 // and added custom functions related to Alkemi pragma solidity 0.4.24; /** * @title Careful Math * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol */ contract CarefulMath is ErrorReporter { /** * @dev Multiplies two numbers, returns an error on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (a == 0) { return (Error.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (Error.INTEGER_OVERFLOW, 0); } else { return (Error.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b == 0) { return (Error.DIVISION_BY_ZERO, 0); } return (Error.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b <= a) { return (Error.NO_ERROR, a - b); } else { return (Error.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function add(uint256 a, uint256 b) internal pure returns (Error, uint256) { uint256 c = a + b; if (c >= a) { return (Error.NO_ERROR, c); } else { return (Error.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSub( uint256 a, uint256 b, uint256 c ) internal pure returns (Error, uint256) { (Error err0, uint256 sum) = add(a, b); if (err0 != Error.NO_ERROR) { return (err0, 0); } return sub(sum, c); } } // File: contracts/Exponential.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; contract Exponential is ErrorReporter, CarefulMath { // Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables // the optimizer MAY replace the expression 10**18 with its calculated value. uint256 constant expScale = 10**18; uint256 constant halfExpScale = expScale / 2; struct Exp { uint256 mantissa; } uint256 constant mantissaOne = 10**18; // Though unused, the below variable cannot be deleted as it will hinder upgradeability // Will be cleared during the next compiler version upgrade uint256 constant mantissaOneTenth = 10**17; /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledNumerator) = mul(num, expScale); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (Error err1, uint256 rational) = div(scaledNumerator, denom); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = add(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = sub(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledMantissa) = mul(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 descaledMantissa) = div(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp divisor) internal pure returns (Error, Exp memory) { /* We are doing this as: getExp(mul(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (Error err0, uint256 numerator) = mul(expScale, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error err0, uint256 doubleScaledProduct) = mul(a.mantissa, b.mantissa); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (Error err1, uint256 doubleScaledProductWithHalfScale) = add( halfExpScale, doubleScaledProduct ); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (Error err2, uint256 product) = div( doubleScaledProductWithHalfScale, expScale ); // The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == Error.NO_ERROR); return (Error.NO_ERROR, Exp({mantissa: product})); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * (10**18)}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if first Exp is greater than second Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } } // File: contracts/InterestRateModel.sol pragma solidity 0.4.24; /** * @title InterestRateModel Interface * @notice Any interest rate model should derive from this contract. * @dev These functions are specifically not marked `pure` as implementations of this * contract may read from storage variables. */ contract InterestRateModel { /** * @notice Gets the current supply interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the supply interest rate per block scaled by 10e18 */ function getSupplyRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); /** * @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the borrow interest rate per block scaled by 10e18 */ function getBorrowRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); } // File: contracts/EIP20Interface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ // total amount of tokens uint256 public totalSupply; // token decimals uint8 public decimals; // maximum is 18 decimals /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view returns (uint256 balance); /** * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) public returns (bool success); /** * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool success); /** * @notice `msg.sender` approves `_spender` to spend `_value` tokens * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint256 _value) public returns (bool success); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/EIP20NonStandardInterface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ contract EIP20NonStandardInterface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ // total amount of tokens uint256 public totalSupply; /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view returns (uint256 balance); /** * !!!!!!!!!!!!!! * !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) public; /** * * !!!!!!!!!!!!!! * !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom( address _from, address _to, uint256 _value ) public; /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/SafeToken.sol pragma solidity 0.4.24; contract SafeToken is ErrorReporter { /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn( address asset, address from, uint256 amount ) internal view returns (Error) { EIP20Interface token = EIP20Interface(asset); if (token.allowance(from, address(this)) < amount) { return Error.TOKEN_INSUFFICIENT_ALLOWANCE; } if (token.balanceOf(from) < amount) { return Error.TOKEN_INSUFFICIENT_BALANCE; } return Error.NO_ERROR; } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory * error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to * insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call, * and it returned Error.NO_ERROR, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn( address asset, address from, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transferFrom(from, address(this), amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_FAILED; } return Error.NO_ERROR; } /** * @dev Checks balance of this contract in asset */ function getCash(address asset) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(address(this)); } /** * @dev Checks balance of `from` in `asset` */ function getBalanceOf(address asset, address from) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(from); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut( address asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transfer(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } function doApprove( address asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.approve(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } } // File: contracts/AggregatorV3Interface.sol pragma solidity 0.4.24; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File: contracts/ChainLink.sol pragma solidity 0.4.24; contract ChainLink { mapping(address => AggregatorV3Interface) internal priceContractMapping; address public admin; bool public paused = false; address public wethAddressVerified; address public wethAddressPublic; AggregatorV3Interface public USDETHPriceFeed; uint256 constant expScale = 10**18; uint8 constant eighteen = 18; /** * Sets the admin * Add assets and set Weth Address using their own functions */ constructor() public { admin = msg.sender; } /** * Modifier to restrict functions only by admins */ modifier onlyAdmin() { require( msg.sender == admin, "Only the Admin can perform this operation" ); _; } /** * Event declarations for all the operations of this contract */ event assetAdded( address indexed assetAddress, address indexed priceFeedContract ); event assetRemoved(address indexed assetAddress); event adminChanged(address indexed oldAdmin, address indexed newAdmin); event verifiedWethAddressSet(address indexed wethAddressVerified); event publicWethAddressSet(address indexed wethAddressPublic); event contractPausedOrUnpaused(bool currentStatus); /** * Allows admin to add a new asset for price tracking */ function addAsset(address assetAddress, address priceFeedContract) public onlyAdmin { require( assetAddress != address(0) && priceFeedContract != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface( priceFeedContract ); emit assetAdded(assetAddress, priceFeedContract); } /** * Allows admin to remove an existing asset from price tracking */ function removeAsset(address assetAddress) public onlyAdmin { require( assetAddress != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface(address(0)); emit assetRemoved(assetAddress); } /** * Allows admin to change the admin of the contract */ function changeAdmin(address newAdmin) public onlyAdmin { require( newAdmin != address(0), "Asset or Price Feed address cannot be 0x00" ); emit adminChanged(admin, newAdmin); admin = newAdmin; } /** * Allows admin to set the weth address for verified protocol */ function setWethAddressVerified(address _wethAddressVerified) public onlyAdmin { require(_wethAddressVerified != address(0), "WETH address cannot be 0x00"); wethAddressVerified = _wethAddressVerified; emit verifiedWethAddressSet(_wethAddressVerified); } /** * Allows admin to set the weth address for public protocol */ function setWethAddressPublic(address _wethAddressPublic) public onlyAdmin { require(_wethAddressPublic != address(0), "WETH address cannot be 0x00"); wethAddressPublic = _wethAddressPublic; emit publicWethAddressSet(_wethAddressPublic); } /** * Allows admin to pause and unpause the contract */ function togglePause() public onlyAdmin { if (paused) { paused = false; emit contractPausedOrUnpaused(false); } else { paused = true; emit contractPausedOrUnpaused(true); } } /** * Returns the latest price scaled to 1e18 scale */ function getAssetPrice(address asset) public view returns (uint256, uint8) { // Return 1 * 10^18 for WETH, otherwise return actual price if (!paused) { if ( asset == wethAddressVerified || asset == wethAddressPublic ){ return (expScale, eighteen); } } // Capture the decimals in the ERC20 token uint8 assetDecimals = EIP20Interface(asset).decimals(); if (!paused && priceContractMapping[asset] != address(0)) { ( uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound ) = priceContractMapping[asset].latestRoundData(); startedAt; // To avoid compiler warnings for unused local variable // If the price data was not refreshed for the past 1 day, prices are considered stale // This threshold is the maximum Chainlink uses to update the price feeds require(timeStamp > (now - 86500 seconds), "Stale data"); // If answeredInRound is less than roundID, prices are considered stale require(answeredInRound >= roundID, "Stale Data"); if (price > 0) { // Magnify the result based on decimals return (uint256(price), assetDecimals); } else { return (0, assetDecimals); } } else { return (0, assetDecimals); } } function() public payable { require( msg.sender.send(msg.value), "Fallback function initiated but refund failed" ); } } // File: contracts/AlkemiWETH.sol // Cloned from https://github.com/gnosis/canonical-weth/blob/master/contracts/WETH9.sol -> Commit id: 0dd1ea3 pragma solidity 0.4.24; contract AlkemiWETH { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); emit Transfer(address(0), msg.sender, msg.value); } function withdraw(address user, uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; user.transfer(wad); emit Withdrawal(msg.sender, wad); emit Transfer(msg.sender, address(0), wad); } function totalSupply() public view returns (uint256) { return address(this).balance; } function approve(address guy, uint256 wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint256 wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } // File: contracts/RewardControlInterface.sol pragma solidity 0.4.24; contract RewardControlInterface { /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external; /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external; /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external; /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address market, bool isVerified ) external; } // File: contracts/AlkemiEarnVerified.sol pragma solidity 0.4.24; contract AlkemiEarnVerified is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnVerified` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: 125 * (10**16)}); originationFee = Exp({mantissa: (10**15)}); liquidationDiscount = Exp({mantissa: (10**17)}); // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnVerified, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Modifier to check if the caller is the admin of the contract */ modifier onlyOwner() { require(msg.sender == admin, "Owner check failed"); _; } /** * @dev Modifier to check if the caller is KYC verified */ modifier onlyCustomerWithKYC() { require( customersWithKYC[msg.sender], "KYC_CUSTOMER_VERIFICATION_CHECK_FAILED" ); _; } /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * @dev Mapping to identify the list of KYC Admins */ mapping(address => bool) public KYCAdmins; /** * @dev Mapping to identify the list of customers with verified KYC */ mapping(address => bool) public customersWithKYC; /** * @dev Mapping to identify the list of customers with Liquidator roles */ mapping(address => bool) public liquidators; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp borrowTotalValue; Exp sumBorrows; Exp supplyTotalValue; Exp sumSupplies; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev Events to notify the frontend of all the functions below */ event LiquidatorChanged(address indexed Liquidator, bool newStatus); /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address account, address asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev KYC Integration */ /** * @dev Events to notify the frontend of all the functions below */ event KYCAdminChanged(address indexed KYCAdmin, bool newStatus); event KYCCustomerChanged(address indexed KYCCustomer, bool newStatus); /** * @dev Function for use by the admin of the contract to add or remove KYC Admins */ function _changeKYCAdmin(address KYCAdmin, bool newStatus) public onlyOwner { KYCAdmins[KYCAdmin] = newStatus; emit KYCAdminChanged(KYCAdmin, newStatus); } /** * @dev Function for use by the KYC admins to add or remove KYC Customers */ function _changeCustomerKYC(address customer, bool newStatus) public { require(KYCAdmins[msg.sender], "KYC_ADMIN_CHECK_FAILED"); customersWithKYC[customer] = newStatus; emit KYCCustomerChanged(customer, newStatus); } /** * @dev Liquidator Integration */ /** * @dev Function for use by the admin of the contract to add or remove Liquidators */ function _changeLiquidator(address liquidator, bool newStatus) public onlyOwner { liquidators[liquidator] = newStatus; emit LiquidatorChanged(liquidator, newStatus); } /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @dev Calculates a new supply index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount( address asset, uint256 assetAmount, bool mulCollatRatio ) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } if (mulCollatRatio) { Exp memory scaledPrice; // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @param newCloseFactorMantissa new Close Factor, scaled by 1e18 * @param wethContractAddress WETH Contract Address * @param _rewardControl Reward Control Address * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa, address wethContractAddress, address _rewardControl ) public onlyOwner returns (uint256) { // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; originationFee = Exp({mantissa: originationFeeMantissa}); closeFactorMantissa = newCloseFactorMantissa; require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); rewardControl = RewardControlInterface(_rewardControl); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function _acceptAdmin() public { // Check caller = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public onlyOwner returns (uint256) { // Hard cap on the maximum number of markets allowed require( interestRateModel != address(0) && collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "INPUT_VALIDATION_FAILED" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public onlyOwner returns (uint256) { // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public onlyOwner returns (uint256) { // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); revertIfError(err); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public onlyOwner returns (uint256) { require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public onlyOwner returns (uint256) { // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. uint256 cash = getCash(asset); // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate(asset, cash - amount, markets[asset].totalSupply); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate(asset, cash - amount, markets[asset].totalBorrows); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH */ function supplyEther(uint256 etherAmount) internal returns (uint256) { require(wethAddress != address(0), "WETH_ADDRESS_NOT_SET_ERROR"); WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount, false ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); revertIfError(err); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); revertIfError(err); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent, false ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent, false ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, false, true); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(localResults.repayAmount); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } require(liquidators[msg.sender], "LIQUIDATOR_CHECK_FAILED"); refreshAlkIndex(assetCollateral, targetAccount, true, true); refreshAlkIndex(assetCollateral, msg.sender, true, true); refreshAlkIndex(assetBorrow, targetAccount, false, true); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice revertIfError(err); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow revertIfError(err); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. revertIfError(err); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET revertIfError(err); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either revertIfError(err); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. revertIfError(err); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, false, true); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmount( asset, localResults.borrowAmountWithFee, true ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkIndex(asset, admin, true, true); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyReceived( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param user The address of the supplier/borrower to accrue rewards * @param isSupply Specifies if Supply or Borrow Index need to be updated * @param isVerified Verified / Public protocol */ function refreshAlkIndex( address market, address user, bool isSupply, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } if (isSupply) { rewardControl.refreshAlkSupplyIndex(market, user, isVerified); } else { rewardControl.refreshAlkBorrowIndex(market, user, isVerified); } } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/AlkemiEarnPublic.sol pragma solidity 0.4.24; contract AlkemiEarnPublic is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnPublic` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; defaultOriginationFee = (10**15); // default is 0.1% defaultCollateralRatio = 125 * (10**16); // default is 125% or 1.25 defaultLiquidationDiscount = (10**17); // default is 10% or 0.1 minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: defaultCollateralRatio}); originationFee = Exp({mantissa: defaultOriginationFee}); liquidationDiscount = Exp({mantissa: defaultLiquidationDiscount}); _guardCounter = 1; // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnPublic, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp supplyTotalValue; Exp sumSupplies; Exp borrowTotalValue; Exp sumBorrows; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a origination fee supply is received as admin * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyOrgFeeAsAdmin( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address indexed oldAdmin, address indexed newAdmin); /** * @dev emitted when new market is supported by admin */ event SupportedMarket( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when risk parameters are changed by admin */ event NewRiskParameters( uint256 oldCollateralRatioMantissa, uint256 newCollateralRatioMantissa, uint256 oldLiquidationDiscountMantissa, uint256 newLiquidationDiscountMantissa ); /** * @dev emitted when origination fee is changed by admin */ event NewOriginationFee( uint256 oldOriginationFeeMantissa, uint256 newOriginationFeeMantissa ); /** * @dev emitted when market has new interest rate model set */ event SetMarketInterestRateModel( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @notice return the number of elements in `collateralMarkets` * @dev you can then externally call `collateralMarkets(uint)` to pull each market address * @return the length of `collateralMarkets` */ function getCollateralMarketsLength() public view returns (uint256) { return collateralMarkets.length; } /** * @dev Calculates a new supply/borrow index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply/borrow index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount(address asset, uint256 assetAmount) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Gets the price for the amount specified of the given asset multiplied by the current * collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth). * We will group this as `(oraclePrice * collateralRatio) * assetAmountWei` * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmountMulCollatRatio( address asset, uint256 assetAmount ) internal view returns (Error, Exp memory) { Error err; Exp memory assetPrice; Exp memory scaledPrice; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_PENDING_ADMIN_OWNER_CHECK"); // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; // Save current value so we can emit it in log. Exp memory oldOriginationFee = originationFee; originationFee = Exp({mantissa: originationFeeMantissa}); emit NewOriginationFee( oldOriginationFee.mantissa, originationFeeMantissa ); closeFactorMantissa = newCloseFactorMantissa; return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint256) { // Check caller = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Save current value for inclusion in log address oldAdmin = admin; // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; emit NewAdmin(oldAdmin, msg.sender); return uint256(Error.NO_ERROR); } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUPPORT_MARKET_OWNER_CHECK"); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Hard cap on the maximum number of markets allowed require( collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "Exceeding the max number of markets allowed" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } emit SupportedMarket(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUSPEND_MARKET_OWNER_CHECK"); // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_RISK_PARAMETERS_OWNER_CHECK"); // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Save current values so we can emit them in log. Exp memory oldCollateralRatio = collateralRatio; Exp memory oldLiquidationDiscount = liquidationDiscount; // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; emit NewRiskParameters( oldCollateralRatio.mantissa, collateralRatioMantissa, oldLiquidationDiscount.mantissa, liquidationDiscountMantissa ); return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK" ); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; emit SetMarketInterestRateModel(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK"); // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate( asset, getCash(asset) - amount, markets[asset].totalSupply ); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate( asset, getCash(asset) - amount, markets[asset].totalBorrows ); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Set WETH token contract address * @param wethContractAddress Enter the WETH token address */ function setWethAddress(address wethContractAddress) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_WETH_ADDRESS_ADMIN_CHECK_FAILED"); require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); return uint256(Error.NO_ERROR); } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function supplyEther(address user, uint256 etherAmount) internal returns (uint256) { user; // To silence the warning of unused local variable if (wethAddress != address(0)) { WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } else { return uint256(Error.WETH_ADDRESS_NOT_SET_ERROR); } } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.sender, msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkBorrowIndex(asset, msg.sender, false); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther( msg.sender, localResults.repayAmount ); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(assetCollateral, targetAccount, false); refreshAlkSupplyIndex(assetCollateral, msg.sender, false); refreshAlkBorrowIndex(assetBorrow, targetAccount, false); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice assert(err == Error.NO_ERROR); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow assert(err == Error.NO_ERROR); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. assert(err == Error.NO_ERROR); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET assert(err == Error.NO_ERROR); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either assert(err == Error.NO_ERROR); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. assert(err == Error.NO_ERROR); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkBorrowIndex(asset, msg.sender, false); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmountMulCollatRatio( asset, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkSupplyIndex(asset, admin, false); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyOrgFeeAsAdmin( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Set the address of the Reward Control contract to be triggered to accrue ALK rewards for participants * @param _rewardControl The address of the underlying reward control contract * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function setRewardControlAddress(address _rewardControl) external returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_REWARD_CONTROL_ADDRESS_ADMIN_CHECK_FAILED" ); require( address(rewardControl) != _rewardControl, "The same Reward Control address" ); require( _rewardControl != address(0), "RewardControl address cannot be empty" ); rewardControl = RewardControlInterface(_rewardControl); return uint256(Error.NO_ERROR); // success } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param supplier The address of the supplier to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkSupplyIndex(market, supplier, isVerified); } /** * @notice Trigger the underlying Reward Control contract to accrue ALK borrow rewards for the borrower on the specified market * @param market The address of the market to accrue rewards * @param borrower The address of the borrower to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkBorrowIndex(market, borrower, isVerified); } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/RewardControlStorage.sol pragma solidity 0.4.24; contract RewardControlStorage { struct MarketState { // @notice The market's last updated alkSupplyIndex or alkBorrowIndex uint224 index; // @notice The block number the index was last updated at uint32 block; } // @notice A list of all markets in the reward program mapped to respective verified/public protocols // @notice true => address[] represents Verified Protocol markets // @notice false => address[] represents Public Protocol markets mapping(bool => address[]) public allMarkets; // @notice The index for checking whether a market is already in the reward program // @notice The first mapping represents verified / public market and the second gives the existence of the market mapping(bool => mapping(address => bool)) public allMarketsIndex; // @notice The rate at which the Reward Control distributes ALK per block uint256 public alkRate; // @notice The portion of alkRate that each market currently receives // @notice The first mapping represents verified / public market and the second gives the alkSpeeds mapping(bool => mapping(address => uint256)) public alkSpeeds; // @notice The ALK market supply state for each market // @notice The first mapping represents verified / public market and the second gives the supplyState mapping(bool => mapping(address => MarketState)) public alkSupplyState; // @notice The ALK market borrow state for each market // @notice The first mapping represents verified / public market and the second gives the borrowState mapping(bool => mapping(address => MarketState)) public alkBorrowState; // @notice The snapshot of ALK index for each market for each supplier as of the last time they accrued ALK // @notice verified/public => market => supplier => supplierIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkSupplierIndex; // @notice The snapshot of ALK index for each market for each borrower as of the last time they accrued ALK // @notice verified/public => market => borrower => borrowerIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkBorrowerIndex; // @notice The ALK accrued but not yet transferred to each participant mapping(address => uint256) public alkAccrued; // @notice To make sure initializer is called only once bool public initializationDone; // @notice The address of the current owner of this contract address public owner; // @notice The proposed address of the new owner of this contract address public newOwner; // @notice The underlying AlkemiEarnVerified contract AlkemiEarnVerified public alkemiEarnVerified; // @notice The underlying AlkemiEarnPublic contract AlkemiEarnPublic public alkemiEarnPublic; // @notice The ALK token address address public alkAddress; // Hard cap on the maximum number of markets uint8 public MAXIMUM_NUMBER_OF_MARKETS; } // File: contracts/ExponentialNoError.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // File: contracts/RewardControl.sol pragma solidity 0.4.24; contract RewardControl is RewardControlStorage, RewardControlInterface, ExponentialNoError { /** * Events */ /// @notice Emitted when a new ALK speed is calculated for a market event AlkSpeedUpdated( address indexed market, uint256 newSpeed, bool isVerified ); /// @notice Emitted when ALK is distributed to a supplier event DistributedSupplierAlk( address indexed market, address indexed supplier, uint256 supplierDelta, uint256 supplierAccruedAlk, uint256 supplyIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is distributed to a borrower event DistributedBorrowerAlk( address indexed market, address indexed borrower, uint256 borrowerDelta, uint256 borrowerAccruedAlk, uint256 borrowIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is transferred to a participant event TransferredAlk( address indexed participant, uint256 participantAccrued, address market, bool isVerified ); /// @notice Emitted when the owner of the contract is updated event OwnerUpdate(address indexed owner, address indexed newOwner); /// @notice Emitted when a market is added event MarketAdded( address indexed market, uint256 numberOfMarkets, bool isVerified ); /// @notice Emitted when a market is removed event MarketRemoved( address indexed market, uint256 numberOfMarkets, bool isVerified ); /** * Constants */ /** * Constructor */ /** * @notice `RewardControl` is the contract to calculate and distribute reward tokens * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only in a derived contract of RewardControlStorage, inherited by this contract * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer( address _owner, address _alkemiEarnVerified, address _alkemiEarnPublic, address _alkAddress ) public { require( _owner != address(0) && _alkemiEarnVerified != address(0) && _alkemiEarnPublic != address(0) && _alkAddress != address(0), "Inputs cannot be 0x00" ); if (initializationDone == false) { initializationDone = true; owner = _owner; alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); alkAddress = _alkAddress; // Total Liquidity rewards for 4 years = 70,000,000 // Liquidity per year = 70,000,000/4 = 17,500,000 // Divided by blocksPerYear (assuming 13.3 seconds avg. block time) = 17,500,000/2,371,128 = 7.380453522542860000 // 7380453522542860000 (Tokens scaled by token decimals of 18) divided by 2 (half for lending and half for borrowing) alkRate = 3690226761271430000; MAXIMUM_NUMBER_OF_MARKETS = 16; } } /** * Modifiers */ /** * @notice Make sure that the sender is only the owner of the contract */ modifier onlyOwner() { require(msg.sender == owner, "non-owner"); _; } /** * Public functions */ /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, supplier, isVerified); } /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, borrower, isVerified); } /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external { claimAlk(holder, allMarkets[true], true); claimAlk(holder, allMarkets[false], false); } /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Specifies if the market is from verified or public protocol */ function claimAlk( address holder, address market, bool isVerified ) external { require(allMarketsIndex[isVerified][market], "Market does not exist"); address[] memory markets = new address[](1); markets[0] = market; claimAlk(holder, markets, isVerified); } /** * Private functions */ /** * @notice Recalculate and update ALK speeds for all markets */ function refreshMarketLiquidity() internal view returns (Exp[] memory, Exp memory) { Exp memory totalLiquidity = Exp({mantissa: 0}); Exp[] memory marketTotalLiquidity = new Exp[]( add_(allMarkets[true].length, allMarkets[false].length) ); address currentMarket; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; uint256 currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); uint256 currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); Exp memory currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[i] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[ verifiedMarketsLength + j ] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } return (marketTotalLiquidity, totalLiquidity); } /** * @notice Recalculate and update ALK speeds for all markets */ function refreshAlkSpeeds() public { address currentMarket; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 newSpeed; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; alkSpeeds[true][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, true); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; newSpeed = totalLiquidity.mantissa > 0 ? mul_( alkRate, div_( marketTotalLiquidity[verifiedMarketsLength + j], totalLiquidity ) ) : 0; alkSpeeds[false][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, false); } } /** * @notice Accrue ALK to the market by updating the supply index * @param market The market whose supply index to update * @param isVerified Verified / Public protocol */ function updateAlkSupplyIndex(address market, bool isVerified) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(supplyState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalSupply = getMarketTotalSupply( market, isVerified ); uint256 supplyAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalSupply > 0 ? fraction(supplyAlkAccrued, marketTotalSupply) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: supplyState.index}), ratio ); alkSupplyState[isVerified][market] = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32( blockNumber, "block number exceeds 32 bits" ); } } /** * @notice Accrue ALK to the market by updating the borrow index * @param market The market whose borrow index to update * @param isVerified Verified / Public protocol */ function updateAlkBorrowIndex(address market, bool isVerified) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(borrowState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalBorrows = getMarketTotalBorrows( market, isVerified ); uint256 borrowAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalBorrows > 0 ? fraction(borrowAlkAccrued, marketTotalBorrows) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: borrowState.index}), ratio ); alkBorrowState[isVerified][market] = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32( blockNumber, "block number exceeds 32 bits" ); } } /** * @notice Calculate ALK accrued by a supplier and add it on top of alkAccrued[supplier] * @param market The market in which the supplier is interacting * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeSupplierAlk( address market, address supplier, bool isVerified ) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({ mantissa: alkSupplierIndex[isVerified][market][supplier] }); alkSupplierIndex[isVerified][market][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa > 0) { Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierBalance = getSupplyBalance( market, supplier, isVerified ); uint256 supplierDelta = mul_(supplierBalance, deltaIndex); alkAccrued[supplier] = add_(alkAccrued[supplier], supplierDelta); emit DistributedSupplierAlk( market, supplier, supplierDelta, alkAccrued[supplier], supplyIndex.mantissa, isVerified ); } } /** * @notice Calculate ALK accrued by a borrower and add it on top of alkAccrued[borrower] * @param market The market in which the borrower is interacting * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeBorrowerAlk( address market, address borrower, bool isVerified ) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({ mantissa: alkBorrowerIndex[isVerified][market][borrower] }); alkBorrowerIndex[isVerified][market][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerBalance = getBorrowBalance( market, borrower, isVerified ); uint256 borrowerDelta = mul_(borrowerBalance, deltaIndex); alkAccrued[borrower] = add_(alkAccrued[borrower], borrowerDelta); emit DistributedBorrowerAlk( market, borrower, borrowerDelta, alkAccrued[borrower], borrowIndex.mantissa, isVerified ); } } /** * @notice Claim all the ALK accrued by holder in the specified markets * @param holder The address to claim ALK for * @param markets The list of markets to claim ALK in * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address[] memory markets, bool isVerified ) internal { for (uint256 i = 0; i < markets.length; i++) { address market = markets[i]; updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, holder, isVerified); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, holder, isVerified); alkAccrued[holder] = transferAlk( holder, alkAccrued[holder], market, isVerified ); } } /** * @notice Transfer ALK to the participant * @dev Note: If there is not enough ALK, we do not perform the transfer all. * @param participant The address of the participant to transfer ALK to * @param participantAccrued The amount of ALK to (possibly) transfer * @param market Market for which ALK is transferred * @param isVerified Verified / Public Protocol * @return The amount of ALK which was NOT transferred to the participant */ function transferAlk( address participant, uint256 participantAccrued, address market, bool isVerified ) internal returns (uint256) { if (participantAccrued > 0) { EIP20Interface alk = EIP20Interface(getAlkAddress()); uint256 alkRemaining = alk.balanceOf(address(this)); if (participantAccrued <= alkRemaining) { alk.transfer(participant, participantAccrued); emit TransferredAlk( participant, participantAccrued, market, isVerified ); return 0; } } return participantAccrued; } /** * Getters */ /** * @notice Get the current block number * @return The current block number */ function getBlockNumber() public view returns (uint256) { return block.number; } /** * @notice Get the current accrued ALK for a participant * @param participant The address of the participant * @return The amount of accrued ALK for the participant */ function getAlkAccrued(address participant) public view returns (uint256) { return alkAccrued[participant]; } /** * @notice Get the address of the ALK token * @return The address of ALK token */ function getAlkAddress() public view returns (address) { return alkAddress; } /** * @notice Get the address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract * @return The address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract */ function getAlkemiEarnAddress() public view returns (address, address) { return (address(alkemiEarnVerified), address(alkemiEarnPublic)); } /** * @notice Get market statistics from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market statistics for the given market */ function getMarketStats(address market, bool isVerified) public view returns ( bool isSupported, uint256 blockNumber, address interestRateModel, uint256 totalSupply, uint256 supplyRateMantissa, uint256 supplyIndex, uint256 totalBorrows, uint256 borrowRateMantissa, uint256 borrowIndex ) { if (isVerified) { return (alkemiEarnVerified.markets(market)); } else { return (alkemiEarnPublic.markets(market)); } } /** * @notice Get market total supply from the AlkemiEarnVerified / AlkemiEarnPublic contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total supply for the given market */ function getMarketTotalSupply(address market, bool isVerified) public view returns (uint256) { uint256 totalSupply; (, , , totalSupply, , , , , ) = getMarketStats(market, isVerified); return totalSupply; } /** * @notice Get market total borrows from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total borrows for the given market */ function getMarketTotalBorrows(address market, bool isVerified) public view returns (uint256) { uint256 totalBorrows; (, , , , , , totalBorrows, , ) = getMarketStats(market, isVerified); return totalBorrows; } /** * @notice Get supply balance of the specified market and supplier * @param market The address of the market * @param supplier The address of the supplier * @param isVerified Verified / Public protocol * @return Supply balance of the specified market and supplier */ function getSupplyBalance( address market, address supplier, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getSupplyBalance(supplier, market); } else { return alkemiEarnPublic.getSupplyBalance(supplier, market); } } /** * @notice Get borrow balance of the specified market and borrower * @param market The address of the market * @param borrower The address of the borrower * @param isVerified Verified / Public protocol * @return Borrow balance of the specified market and borrower */ function getBorrowBalance( address market, address borrower, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getBorrowBalance(borrower, market); } else { return alkemiEarnPublic.getBorrowBalance(borrower, market); } } /** * Admin functions */ /** * @notice Transfer the ownership of this contract to the new owner. The ownership will not be transferred until the new owner accept it. * @param _newOwner The address of the new owner */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != owner, "TransferOwnership: the same owner."); newOwner = _newOwner; } /** * @notice Accept the ownership of this contract by the new owner */ function acceptOwnership() external { require( msg.sender == newOwner, "AcceptOwnership: only new owner do this." ); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } /** * @notice Add new market to the reward program * @param market The address of the new market to be added to the reward program * @param isVerified Verified / Public protocol */ function addMarket(address market, bool isVerified) external onlyOwner { require(!allMarketsIndex[isVerified][market], "Market already exists"); require( allMarkets[isVerified].length < uint256(MAXIMUM_NUMBER_OF_MARKETS), "Exceeding the max number of markets allowed" ); allMarketsIndex[isVerified][market] = true; allMarkets[isVerified].push(market); emit MarketAdded( market, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Remove a market from the reward program based on array index * @param id The index of the `allMarkets` array to be removed * @param isVerified Verified / Public protocol */ function removeMarket(uint256 id, bool isVerified) external onlyOwner { if (id >= allMarkets[isVerified].length) { return; } allMarketsIndex[isVerified][allMarkets[isVerified][id]] = false; address removedMarket = allMarkets[isVerified][id]; for (uint256 i = id; i < allMarkets[isVerified].length - 1; i++) { allMarkets[isVerified][i] = allMarkets[isVerified][i + 1]; } allMarkets[isVerified].length--; // reset the ALK speeds for the removed market and refresh ALK speeds alkSpeeds[isVerified][removedMarket] = 0; refreshAlkSpeeds(); emit MarketRemoved( removedMarket, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Set ALK token address * @param _alkAddress The ALK token address */ function setAlkAddress(address _alkAddress) external onlyOwner { require(alkAddress != _alkAddress, "The same ALK address"); require(_alkAddress != address(0), "ALK address cannot be empty"); alkAddress = _alkAddress; } /** * @notice Set AlkemiEarnVerified contract address * @param _alkemiEarnVerified The AlkemiEarnVerified contract address */ function setAlkemiEarnVerifiedAddress(address _alkemiEarnVerified) external onlyOwner { require( address(alkemiEarnVerified) != _alkemiEarnVerified, "The same AlkemiEarnVerified address" ); require( _alkemiEarnVerified != address(0), "AlkemiEarnVerified address cannot be empty" ); alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); } /** * @notice Set AlkemiEarnPublic contract address * @param _alkemiEarnPublic The AlkemiEarnVerified contract address */ function setAlkemiEarnPublicAddress(address _alkemiEarnPublic) external onlyOwner { require( address(alkemiEarnPublic) != _alkemiEarnPublic, "The same AlkemiEarnPublic address" ); require( _alkemiEarnPublic != address(0), "AlkemiEarnPublic address cannot be empty" ); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); } /** * @notice Set ALK rate * @param _alkRate The ALK rate */ function setAlkRate(uint256 _alkRate) external onlyOwner { alkRate = _alkRate; } /** * @notice Get latest ALK rewards * @param user the supplier/borrower */ function getAlkRewards(address user) external view returns (uint256) { // Refresh ALK speeds uint256 alkRewards = alkAccrued[user]; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ) ) ); } for (uint256 j = 0; j < allMarkets[false].length; j++) { uint256 index = verifiedMarketsLength + j; alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ) ) ); } return alkRewards; } /** * @notice Get latest Supply ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the supplier * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getSupplyAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory supplyState = alkSupplyState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(supplyState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: supplyState.index}), ( getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(supplyState.block) ), newSpeed ), getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); supplyState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(supplyState.block)) > 0) { supplyState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnVerified.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( !isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnPublic.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } /** * @notice Get latest Borrow ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the borrower * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getBorrowAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory borrowState = alkBorrowState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(borrowState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: borrowState.index}), ( getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(borrowState.block) ), newSpeed ), getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); borrowState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(borrowState.block)) > 0) { borrowState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && isVerified ) { return mul_( alkemiEarnVerified.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && !isVerified ) { return mul_( alkemiEarnPublic.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } }
* @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] (Oracle price for the collateral / Oracle price for the borrow) @return Return values are expressed in 1e18 scale/ To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ]
function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { Error err; Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); }
81,167
[ 1, 23650, 329, 38, 15318, 8517, 362, 7458, 13535, 2045, 287, 273, 306, 2859, 1283, 3935, 342, 261, 21, 397, 4501, 26595, 367, 9866, 25887, 225, 261, 23601, 6205, 364, 326, 4508, 2045, 287, 342, 28544, 6205, 364, 326, 29759, 13, 327, 2000, 924, 854, 26863, 316, 404, 73, 2643, 3159, 19, 2974, 4543, 13885, 8296, 16, 732, 283, 17, 1019, 471, 1041, 326, 5295, 1427, 732, 741, 404, 16536, 471, 1338, 622, 326, 679, 306, 2859, 1283, 3935, 225, 261, 23601, 6205, 364, 326, 4508, 2045, 287, 25887, 342, 306, 261, 21, 397, 4501, 26595, 367, 9866, 13, 225, 261, 23601, 6205, 364, 326, 29759, 13, 308, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 9866, 329, 38, 15318, 8517, 362, 7458, 13535, 2045, 287, 12, 203, 3639, 7784, 3778, 3613, 91, 2045, 6672, 5147, 16, 203, 3639, 7784, 3778, 4508, 2045, 287, 5147, 16, 203, 3639, 2254, 5034, 14467, 3935, 67, 2326, 13535, 2045, 287, 6672, 203, 565, 262, 2713, 1476, 1135, 261, 668, 16, 2254, 5034, 13, 288, 203, 3639, 1068, 393, 31, 203, 3639, 7784, 3778, 1831, 1253, 31, 203, 203, 3639, 261, 370, 16, 1245, 13207, 48, 18988, 350, 367, 9866, 13, 273, 527, 2966, 12, 203, 5411, 4501, 26595, 367, 9866, 203, 3639, 11272, 203, 3639, 309, 261, 370, 480, 1068, 18, 3417, 67, 3589, 13, 288, 203, 5411, 327, 261, 370, 16, 374, 1769, 203, 3639, 289, 203, 203, 3639, 261, 370, 16, 14467, 3935, 10694, 23601, 13535, 2045, 287, 13, 273, 14064, 13639, 12, 203, 5411, 4508, 2045, 287, 5147, 16, 203, 5411, 14467, 3935, 67, 2326, 13535, 2045, 287, 6672, 203, 3639, 11272, 203, 3639, 309, 261, 370, 480, 1068, 18, 3417, 67, 3589, 13, 288, 203, 5411, 327, 261, 370, 16, 374, 1769, 203, 3639, 289, 203, 203, 3639, 261, 370, 16, 1245, 13207, 48, 18988, 350, 367, 9866, 10694, 23601, 38, 15318, 13, 273, 14064, 2966, 12, 203, 5411, 1245, 13207, 48, 18988, 350, 367, 9866, 16, 203, 5411, 3613, 91, 2045, 6672, 5147, 203, 3639, 11272, 203, 3639, 309, 261, 370, 480, 1068, 18, 3417, 67, 3589, 13, 288, 203, 5411, 327, 261, 370, 16, 374, 1769, 203, 3639, 289, 203, 203, 3639, 261, 370, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.5; import "./TransferHelper.sol"; import "./Ownable.sol"; import "./ReentrancyGuard.sol"; interface Token { function decimals() external view returns (uint256); function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transferFrom( address from, address to, uint256 value ) external returns (bool); } contract Redmars is Ownable, ReentrancyGuard { uint256 public projectCounter; //for counting the number of project struct TokenSale { uint128 numberOfTokenForSale; //number of token user wants to sell uint128 priceOfTokenInBNB; // price of token set by user uint128 StartTime; //to mark the start of campaign uint128 duration; // duration of sale period uint128 numberOfTokenSOLD; // to track how many token got sold uint128 amountRaised; // to keep track of the bnb to give the user at the end of the campaign address tokenAddr; // token address from the campaign address ownerAddress; // owner of the campaign bool isActive; //to check if campaign is active } event invested( address investorAddress, uint256 projectID, uint256 amount, uint128 tokenSold ); mapping(uint256 => TokenSale) public ProjectInfo; address public redmarsAddress; uint128 public minRedmarsAmount; struct UserInfo { uint128 tokenAmount; address tokenAddress; bool isClaimed; } mapping(address => mapping(uint256 => UserInfo)) public userInfoMapping; address public adminAddress; uint128 public adminSharePercentage; //in 10**2 bool isInitialized; function initialize( address owner, address _adminAddress, uint128 _adminSharePercentage, address _redmarsAddress, uint128 _minRedmarsAmount ) public { require(!isInitialized, "Already initialized"); _setOwner(owner); isInitialized = true; adminAddress = _adminAddress; adminSharePercentage = _adminSharePercentage; redmarsAddress = _redmarsAddress; minRedmarsAmount = _minRedmarsAmount; } function requestICO( uint128 _numberOfTokenForSale, uint128 _priceOfTokeninBNB, uint128 _duration, address _tokenAddr ) external nonReentrant { require( (Token(redmarsAddress).balanceOf(msg.sender)) >= minRedmarsAmount, "check your RedMars balance." ); require( Token(_tokenAddr).allowance(msg.sender, address(this)) >= _numberOfTokenForSale, "Approve Tokens." ); // approval not given by from the token contract require( (Token(_tokenAddr).balanceOf(msg.sender)) >= _numberOfTokenForSale, "check your balance." ); //not enough token given for the campaign ++projectCounter; TokenSale memory saleInfo = TokenSale({ numberOfTokenForSale: _numberOfTokenForSale, priceOfTokenInBNB: _priceOfTokeninBNB, StartTime: 0, duration: _duration, numberOfTokenSOLD: 0, amountRaised: 0, tokenAddr: _tokenAddr, ownerAddress: msg.sender, isActive: false }); ProjectInfo[projectCounter] = saleInfo; } function approveICO(uint256 _projectId) external onlyOwner { // to get approval of admin TokenSale memory saleInfo = ProjectInfo[_projectId]; require( Token(saleInfo.tokenAddr).allowance( saleInfo.ownerAddress, address(this) ) >= saleInfo.numberOfTokenForSale, "Approve Tokens." ); require( (Token(saleInfo.tokenAddr).balanceOf(saleInfo.ownerAddress)) >= saleInfo.numberOfTokenForSale, "check your balance." ); ProjectInfo[_projectId].StartTime = (uint128)(block.timestamp); ProjectInfo[_projectId].isActive = true; TransferHelper.safeTransferFrom( saleInfo.tokenAddr, saleInfo.ownerAddress, address(this), saleInfo.numberOfTokenForSale ); } function invest(uint256 _projectId) external payable nonReentrant { require(msg.value > 0, "Enter valid value"); require( (Token(redmarsAddress).balanceOf(msg.sender)) >= minRedmarsAmount, "check your RedMars balance." ); TokenSale storage saleInfo = ProjectInfo[_projectId]; require(saleInfo.isActive, "Not Active"); uint128 tokenSold = uint128(calculateToken(_projectId, msg.value)); require( (saleInfo.duration + saleInfo.StartTime > block.timestamp), "ICO Ended." ); require( ((saleInfo.numberOfTokenSOLD + tokenSold) <= saleInfo.numberOfTokenForSale), "No tokens left." ); UserInfo memory uInfo = UserInfo({ tokenAmount: (( userInfoMapping[msg.sender][_projectId].tokenAmount ) + tokenSold), tokenAddress: saleInfo.tokenAddr, isClaimed: false }); userInfoMapping[msg.sender][_projectId] = uInfo; saleInfo.numberOfTokenSOLD += tokenSold; saleInfo.amountRaised += uint128(msg.value); emit invested(msg.sender, _projectId, msg.value, tokenSold); } function calculateBNB(uint256 _projectId, uint256 _tokenAmount) public view returns (uint256) { TokenSale memory saleInfo = ProjectInfo[_projectId]; return (_tokenAmount * saleInfo.priceOfTokenInBNB) / ((10**Token(saleInfo.tokenAddr).decimals())); // calculating BNB when number of token is given } function calculateToken(uint256 _projectId, uint256 _BNBAmount) public view returns (uint256) { TokenSale memory saleInfo = ProjectInfo[_projectId]; return ((_BNBAmount * (10**Token(saleInfo.tokenAddr).decimals())) / (saleInfo.priceOfTokenInBNB)); // calculating token when number of BNB is given } function claimMoney(uint256 _projectId) external onlyOwner { TokenSale memory saleInfo = ProjectInfo[_projectId]; require(saleInfo.isActive, "Not Active"); require( (saleInfo.duration + saleInfo.StartTime <= block.timestamp) || (saleInfo.numberOfTokenSOLD == saleInfo.numberOfTokenForSale), "ICO Running." ); uint128 adminShare = (((saleInfo.amountRaised) * adminSharePercentage) / 10**4); // admin's cut TransferHelper.safeTransferETH( saleInfo.ownerAddress, saleInfo.amountRaised - adminShare ); //sending BNB to campaigner TransferHelper.safeTransferETH(adminAddress, adminShare); if (saleInfo.numberOfTokenSOLD < saleInfo.numberOfTokenForSale) { TransferHelper.safeTransfer( saleInfo.tokenAddr, saleInfo.ownerAddress, ((saleInfo.numberOfTokenForSale) - (saleInfo.numberOfTokenSOLD)) ); } ProjectInfo[_projectId].isActive = false; // sending BNB to Admin } function updateRedmars(address _redmarsAddress) external onlyOwner { redmarsAddress = _redmarsAddress; } function updateMinRedmarsAmount(uint128 _minRedmarsAmount) external onlyOwner { minRedmarsAmount = _minRedmarsAmount; } function claimUserTokens(uint256 _projectId) external { TokenSale memory saleInfo = ProjectInfo[_projectId]; require( (saleInfo.duration + saleInfo.StartTime <= block.timestamp) || (saleInfo.numberOfTokenSOLD == saleInfo.numberOfTokenForSale), "ICO Running." ); UserInfo storage uInfo = userInfoMapping[msg.sender][_projectId]; require((!uInfo.isClaimed), "Already Claimed"); TransferHelper.safeTransfer( saleInfo.tokenAddr, msg.sender, uInfo.tokenAmount ); uInfo.isClaimed = true; } function updateAdminAddress(address _adminAddress) external onlyOwner { adminAddress = _adminAddress; } function updateAdminSharePercentage(uint128 _adminSharePercentage) external onlyOwner { adminSharePercentage = _adminSharePercentage; } }
for counting the number of project
uint256 public projectCounter;
13,041,514
[ 1, 1884, 22075, 326, 1300, 434, 1984, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 1984, 4789, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// contracts/token/ERC721/sovereign/SovereignNFT.sol // SPDX-License-Identifier: MIT pragma solidity 0.7.3; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "../IERC721Creator.sol"; import "../../../royalty/ERC2981Upgradeable.sol"; contract SovereignNFT is OwnableUpgradeable, ERC165Upgradeable, ERC721Upgradeable, IERC721Creator, ERC721BurnableUpgradeable, ERC2981Upgradeable { using SafeMathUpgradeable for uint256; using CountersUpgradeable for CountersUpgradeable.Counter; bool public disabled; // Mapping from token ID to the creator's address mapping(uint256 => address) private tokenCreators; // Counter to keep track of the current token id. CountersUpgradeable.Counter private tokenIdCounter; // Default royalty percentage uint256 public defaultRoyaltyPercentage; event ContractDisabled(address indexed user); function init( string calldata _name, string calldata _symbol, address _creator ) public initializer { require(_creator != address(0)); defaultRoyaltyPercentage = 10; disabled = false; __Ownable_init(); __ERC721_init(_name, _symbol); __ERC165_init(); __ERC2981__init(); _registerInterface(calcIERC721CreatorInterfaceId()); super.transferOwnership(_creator); } modifier onlyTokenOwner(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender, "Must be owner of token."); _; } modifier ifNotDisabled() { require(!disabled, "Contract must not be disabled."); _; } function addNewToken(string memory _uri) public onlyOwner ifNotDisabled { _createToken(_uri, msg.sender, msg.sender, defaultRoyaltyPercentage); } function mintToWithRoyaltyPercentage( string memory _uri, address _receiver, uint256 _royaltyPercentage ) public onlyOwner ifNotDisabled { _createToken(_uri, msg.sender, _receiver, _royaltyPercentage); } function batchAddNewToken(string[] calldata _uris) public onlyOwner ifNotDisabled { require( _uris.length < 2000, "batchAddNewToken::Cant mint more than 2000 tokens at a time." ); for (uint256 i = 0; i < _uris.length; i++) { _createToken( _uris[0], msg.sender, msg.sender, defaultRoyaltyPercentage ); } } function renounceOwnership() public view override onlyOwner { revert("unsupported"); } function transferOwnership(address) public view override onlyOwner { revert("unsupported"); } function deleteToken(uint256 _tokenId) public onlyTokenOwner(_tokenId) { burn(_tokenId); } function tokenCreator( uint256 // _tokenId ) public view override returns (address payable) { return payable(owner()); } function disableContract() public onlyOwner { disabled = true; emit ContractDisabled(msg.sender); } function _setTokenCreator(uint256 _tokenId, address _creator) internal { tokenCreators[_tokenId] = _creator; } function _createToken( string memory _uri, address _creator, address _to, uint256 _royaltyPercentage ) internal returns (uint256) { tokenIdCounter.increment(); uint256 tokenId = tokenIdCounter.current(); _mint(_to, tokenId); _setTokenURI(tokenId, _uri); _setTokenCreator(tokenId, _creator); _setRoyaltyReceiver(tokenId, _creator); _setRoyaltyPercentage(tokenId, _royaltyPercentage); return tokenId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC721Upgradeable.sol"; import "./IERC721MetadataUpgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/EnumerableSetUpgradeable.sol"; import "../../utils/EnumerableMapUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable for uint256; // 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 holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.UintToAddressMap private _tokenOwners; // 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; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * 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 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * 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; /* * 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 Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @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 _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @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 _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @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 || ERC721Upgradeable.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 _tokenOwners.contains(tokenId); } /** * @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 || ERC721Upgradeable.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `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); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal 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); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @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()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721ReceiverUpgradeable(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } uint256[41] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../utils/ContextUpgradeable.sol"; import "./ERC721Upgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Burnable_init_unchained(); } function __ERC721Burnable_init_unchained() internal initializer { } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * 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 __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal 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 virtual override 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 virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../math/SafeMathUpgradeable.sol"; /** * @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 CountersUpgradeable { using SafeMathUpgradeable 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); } } // contracts/token/ERC721/IERC721Creator.sol // SPDX-License-Identifier: MIT pragma solidity 0.7.3; /** * @title IERC721 Non-Fungible Token Creator basic interface */ abstract contract IERC721Creator { /** * @dev Gets the creator of the token * @param _tokenId uint256 ID of the token * @return address of the creator */ function tokenCreator(uint256 _tokenId) public view virtual returns (address payable); function calcIERC721CreatorInterfaceId() public pure returns (bytes4) { return this.tokenCreator.selector; } } // contracts/royalty/ERC2981.sol // SPDX-License-Identifier: MIT pragma solidity 0.7.3; import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "./IERC2981.sol"; abstract contract ERC2981Upgradeable is IERC2981, ERC165Upgradeable { using SafeMathUpgradeable for uint256; // bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; mapping(uint256 => address) royaltyReceivers; mapping(uint256 => uint256) royaltyPercentages; constructor() {} function __ERC2981__init() internal initializer { __ERC165_init(); _registerInterface(_INTERFACE_ID_ERC2981); } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address receiver, uint256 royaltyAmount) { receiver = royaltyReceivers[_tokenId]; royaltyAmount = _salePrice.mul(royaltyPercentages[_tokenId]).div(100); } function _setRoyaltyReceiver(uint256 _tokenId, address _newReceiver) internal { royaltyReceivers[_tokenId] = _newReceiver; } function _setRoyaltyPercentage(uint256 _tokenId, uint256 _percentage) internal { royaltyPercentages[_tokenId] = _percentage; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/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 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 ContextUpgradeable is Initializable { 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; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../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 pragma solidity ^0.7.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 pragma solidity ^0.7.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 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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 pragma solidity ^0.7.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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { 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 pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMapUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev String operations. */ library StringsUpgradeable { /** * @dev Converts a `uint256` to its ASCII `string` 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); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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); } // contracts/royalty/IERC2981.sol // SPDX-License-Identifier: MIT pragma solidity 0.7.3; /// @dev Interface for the NFT Royalty Standard interface IERC2981 { /// ERC165 bytes to add to interface array - set in parent contract /// implementing this standard /// /// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a /// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; /// _registerInterface(_INTERFACE_ID_ERC2981); /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _salePrice - the sale price of the NFT asset specified by _tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for _salePrice function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount); }
* @title IERC721 Non-Fungible Token Creator basic interface/
abstract contract IERC721Creator { function tokenCreator(uint256 _tokenId) public view virtual returns (address payable); pragma solidity 0.7.3; function calcIERC721CreatorInterfaceId() public pure returns (bytes4) { return this.tokenCreator.selector; } }
14,438,727
[ 1, 45, 654, 39, 27, 5340, 3858, 17, 42, 20651, 1523, 3155, 29525, 5337, 1560, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 467, 654, 39, 27, 5340, 10636, 288, 203, 565, 445, 1147, 10636, 12, 11890, 5034, 389, 2316, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 1135, 261, 2867, 8843, 429, 1769, 203, 203, 683, 9454, 18035, 560, 374, 18, 27, 18, 23, 31, 203, 565, 445, 7029, 45, 654, 39, 27, 5340, 10636, 1358, 548, 1435, 1071, 16618, 1135, 261, 3890, 24, 13, 288, 203, 3639, 327, 333, 18, 2316, 10636, 18, 9663, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; //Slightly modified SafeMath library - includes a min and max function, removes useless div function library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a + b; assert(c >= a); } else { c = a + b; assert(c <= a); } } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } function max(int256 a, int256 b) internal pure returns (uint256) { return a > b ? uint256(a) : uint256(b); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function sub(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a - b; assert(c <= a); } else { c = a - b; assert(c >= a); } } } pragma solidity ^0.5.0; /** * @title Tellor Oracle Storage Library * @dev Contains all the variables/structs used by Tellor */ library TellorStorage { //Internal struct for use in proof-of-work submission struct Details { uint256 value; address miner; } struct Dispute { bytes32 hash; //unique hash of dispute: keccak256(_miner,_requestId,_timestamp) int256 tally; //current tally of votes for - against measure bool executed; //is the dispute settled bool disputeVotePassed; //did the vote pass? bool isPropFork; //true for fork proposal NEW address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes address proposedForkAddress; //new fork address (if fork proposal) mapping(bytes32 => uint256) disputeUintVars; //Each of the variables below is saved in the mapping disputeUintVars for each disputeID //e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")] //These are the variables saved in this mapping: // uint keccak256("requestId");//apiID of disputed value // uint keccak256("timestamp");//timestamp of distputed value // uint keccak256("value"); //the value being disputed // uint keccak256("minExecutionDate");//7 days from when dispute initialized // uint keccak256("numberOfVotes");//the number of parties who have voted on the measure // uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from // uint keccak256("minerSlot"); //index in dispute array // uint keccak256("fee"); //fee paid corresponding to dispute mapping(address => bool) voted; //mapping of address to whether or not they voted } struct StakeInfo { uint256 currentStatus; //0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute 4=ReadyForUnlocking 5=Unlocked uint256 startDate; //stake start date } //Internal struct to allow balances to be queried by blocknumber for voting purposes struct Checkpoint { uint128 fromBlock; // fromBlock is the block number that the value was generated from uint128 value; // value is the amount of tokens at a specific block number } struct Request { string queryString; //id to string api string dataSymbol; //short name for api request bytes32 queryHash; //hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity)) uint256[] requestTimestamps; //array of all newValueTimestamps requested mapping(bytes32 => uint256) apiUintVars; //Each of the variables below is saved in the mapping apiUintVars for each api request //e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")] //These are the variables saved in this mapping: // uint keccak256("granularity"); //multiplier for miners // uint keccak256("requestQPosition"); //index in requestQ // uint keccak256("totalTip");//bonus portion of payout mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number //This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value mapping(uint256 => uint256) finalValues; mapping(uint256 => bool) inDispute; //checks if API id is in dispute or finalized. mapping(uint256 => address[5]) minersByValue; mapping(uint256 => uint256[5]) valuesByTimestamp; } struct TellorStorageStruct { bytes32 currentChallenge; //current challenge to be solved uint256[51] requestQ; //uint50 array of the top50 requests by payment amount uint256[] newValueTimestamps; //array of all timestamps requested Details[5] currentMiners; //This struct is for organizing the five mined values to find the median mapping(bytes32 => address) addressVars; //Address fields in the Tellor contract are saved the addressVars mapping //e.g. addressVars[keccak256("tellorContract")] = address //These are the variables saved in this mapping: // address keccak256("tellorContract");//Tellor address // address keccak256("_owner");//Tellor Owner address // address keccak256("_deity");//Tellor Owner that can do things at will // address keccak256("pending_owner"); // The proposed new owner mapping(bytes32 => uint256) uintVars; //uint fields in the Tellor contract are saved the uintVars mapping //e.g. uintVars[keccak256("decimals")] = uint //These are the variables saved in this mapping: // keccak256("decimals"); //18 decimal standard ERC20 // keccak256("disputeFee");//cost to dispute a mined value // keccak256("disputeCount");//totalHistoricalDisputes // keccak256("total_supply"); //total_supply of the token in circulation // keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?) // keccak256("stakerCount"); //number of parties currently staked // keccak256("timeOfLastNewValue"); // time of last challenge solved // keccak256("difficulty"); // Difficulty of current block // keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool // keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id // keccak256("requestCount"); // total number of requests through the system // keccak256("slotProgress");//Number of miners who have mined this value so far // keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value // keccak256("timeTarget"); //The time between blocks (mined Oracle values) // keccak256("_tblock"); // // keccak256("runningTips"); // VAriable to track running tips // keccak256("currentReward"); // The current reward // keccak256("devShare"); // The amount directed towards th devShare // keccak256("currentTotalTips"); // //This is a boolean that tells you if a given challenge has been completed by a given miner mapping(bytes32 => mapping(address => bool)) minersByChallenge; mapping(uint256 => uint256) requestIdByTimestamp; //minedTimestamp to apiId mapping(uint256 => uint256) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId mapping(uint256 => Dispute) disputesById; //disputeId=> Dispute details mapping(address => Checkpoint[]) balances; //balances of a party given blocks mapping(address => mapping(address => uint256)) allowed; //allowance for a given party and approver mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info mapping(uint256 => Request) requestDetails; //mapping of apiID to details mapping(bytes32 => uint256) requestIdByQueryHash; // api bytes32 gets an id = to count of requests array mapping(bytes32 => uint256) disputeIdByDisputeHash; //maps a hash to an ID for each dispute } } pragma solidity ^0.5.16; /** * @title Tellor Transfer * @dev Contains the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol * reference this library for function's logic. */ library TellorTransfer { using SafeMath for uint256; event Approval(address indexed _owner, address indexed _spender, uint256 _value); //ERC20 Approval event event Transfer(address indexed _from, address indexed _to, uint256 _value); //ERC20 Transfer Event bytes32 public constant stakeAmount = 0x7be108969d31a3f0b261465c71f2b0ba9301cd914d55d9091c3b36a49d4d41b2; //keccak256("stakeAmount") /*Functions*/ /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(TellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) { doTransfer(self, msg.sender, _to, _amount); return true; } /** * @notice Send _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public returns (bool success) { require(self.allowed[_from][msg.sender] >= _amount, "Allowance is wrong"); self.allowed[_from][msg.sender] -= _amount; doTransfer(self, _from, _to, _amount); return true; } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(TellorStorage.TellorStorageStruct storage self, address _spender, uint256 _amount) public returns (bool) { require(_spender != address(0), "Spender is 0-address"); require(self.allowed[msg.sender][_spender] == 0 || _amount == 0, "Spender is already approved"); self.allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @param _user address of party with the balance * @param _spender address of spender of parties said balance * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(TellorStorage.TellorStorageStruct storage self, address _user, address _spender) public view returns (uint256) { return self.allowed[_user][_spender]; } /** * @dev Completes POWO transfers by updating the balances on the current block number * @param _from address to transfer from * @param _to addres to transfer to * @param _amount to transfer */ function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public { require(_amount != 0, "Tried to send non-positive amount"); require(_to != address(0), "Receiver is 0 address"); require(allowedToTrade(self, _from, _amount), "Should have sufficient balance to trade"); uint256 previousBalance = balanceOf(self, _from); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); previousBalance = balanceOf(self,_to); require(previousBalance + _amount >= previousBalance, "Overflow happened"); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); emit Transfer(_from, _to, _amount); } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(TellorStorage.TellorStorageStruct storage self, address _user) public view returns (uint256) { return balanceOfAt(self, _user, block.number); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber specified */ function balanceOfAt(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _blockNumber) public view returns (uint256) { TellorStorage.Checkpoint[] storage checkpoints = self.balances[_user]; if (checkpoints.length == 0|| checkpoints[0].fromBlock > _blockNumber) { return 0; } else { if (_blockNumber >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value; // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length - 2; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock ==_blockNumber){ return checkpoints[mid].value; }else if(checkpoints[mid].fromBlock < _blockNumber) { min = mid; } else { max = mid - 1; } } return checkpoints[min].value; } } /** * @dev This function returns whether or not a given user is allowed to trade a given amount * and removing the staked amount from their balance if they are staked * @param _user address of user * @param _amount to check if the user can spend * @return true if they are allowed to spend the amount being checked */ function allowedToTrade(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _amount) public view returns (bool) { if (self.stakerDetails[_user].currentStatus != 0 && self.stakerDetails[_user].currentStatus < 5) { //Subtracts the stakeAmount from balance if the _user is staked if (balanceOf(self, _user)- self.uintVars[stakeAmount] >= _amount) { return true; } return false; } return (balanceOf(self, _user) >= _amount); } /** * @dev Updates balance for from and to on the current block number via doTransfer * @param checkpoints gets the mapping for the balances[owner] * @param _value is the new balance */ function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint256 _value) public { if (checkpoints.length == 0 || checkpoints[checkpoints.length - 1].fromBlock != block.number) { checkpoints.push(TellorStorage.Checkpoint({ fromBlock : uint128(block.number), value : uint128(_value) })); } else { TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } } pragma solidity ^0.5.16; /** * @title Tellor Dispute * @dev Contains the methods related to disputes. Tellor.sol references this library for function's logic. */ library TellorDispute { using SafeMath for uint256; using SafeMath for int256; //emitted when a new dispute is initialized event NewDispute(uint256 indexed _disputeId, uint256 indexed _requestId, uint256 _timestamp, address _miner); //emitted when a new vote happens event Voted(uint256 indexed _disputeID, bool _position, address indexed _voter, uint256 indexed _voteWeight); //emitted upon dispute tally event DisputeVoteTallied(uint256 indexed _disputeID, int256 _result, address indexed _reportedMiner, address _reportingParty, bool _active); event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) public { TellorStorage.Request storage _request = self.requestDetails[_requestId]; require(_request.minedBlockNum[_timestamp] != 0, "Mined block is 0"); require(_minerIndex < 5, "Miner index is wrong"); //_miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndex //provided by the party initiating the dispute address _miner = _request.minersByValue[_timestamp][_minerIndex]; bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp)); //Increase the dispute count by 1 uint256 disputeId = self.uintVars[keccak256("disputeCount")] + 1; self.uintVars[keccak256("disputeCount")] = disputeId; //Sets the new disputeCount as the disputeId //Ensures that a dispute is not already open for the that miner, requestId and timestamp uint256 hashId = self.disputeIdByDisputeHash[_hash]; if(hashId != 0){ self.disputesById[disputeId].disputeUintVars[keccak256("origID")] = hashId; } else{ self.disputeIdByDisputeHash[_hash] = disputeId; hashId = disputeId; } uint256 origID = hashId; uint256 dispRounds = self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")] + 1; self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")] = dispRounds; self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds))] = disputeId; if(disputeId != origID){ uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds-1))]; require(self.disputesById[lastID].disputeUintVars[keccak256("minExecutionDate")] <= now, "Dispute is already open"); if(self.disputesById[lastID].executed){ require(now - self.disputesById[lastID].disputeUintVars[keccak256("tallyDate")] <= 1 days, "Time for voting haven't elapsed"); } } uint256 _fee; if (_minerIndex == 2) { self.requestDetails[_requestId].apiUintVars[keccak256("disputeCount")] = self.requestDetails[_requestId].apiUintVars[keccak256("disputeCount")] +1; //update dispute fee for this case _fee = self.uintVars[keccak256("stakeAmount")]*self.requestDetails[_requestId].apiUintVars[keccak256("disputeCount")]; } else { _fee = self.uintVars[keccak256("disputeFee")] * dispRounds; } //maps the dispute to the Dispute struct self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, isPropFork: false, reportedMiner: _miner, reportingParty: msg.sender, proposedForkAddress: address(0), executed: false, disputeVotePassed: false, tally: 0 }); //Saves all the dispute variables for the disputeId self.disputesById[disputeId].disputeUintVars[keccak256("requestId")] = _requestId; self.disputesById[disputeId].disputeUintVars[keccak256("timestamp")] = _timestamp; self.disputesById[disputeId].disputeUintVars[keccak256("value")] = _request.valuesByTimestamp[_timestamp][_minerIndex]; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 2 days * dispRounds; self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = _fee; TellorTransfer.doTransfer(self, msg.sender, address(this),_fee); //Values are sorted as they come in and the official value is the median of the first five //So the "official value" miner is always minerIndex==2. If the official value is being //disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute if (_minerIndex == 2) { _request.inDispute[_timestamp] = true; _request.finalValues[_timestamp] = 0; } self.stakerDetails[_miner].currentStatus = 3; emit NewDispute(disputeId, _requestId, _timestamp, _miner); } /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bool _supportsDispute) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; //Get the voteWeight or the balance of the user at the time/blockNumber the disupte began uint256 voteWeight = TellorTransfer.balanceOfAt(self, msg.sender, disp.disputeUintVars[keccak256("blockNumber")]); //Require that the msg.sender has not voted require(disp.voted[msg.sender] != true, "Sender has already voted"); //Requre that the user had a balance >0 at time/blockNumber the disupte began require(voteWeight != 0, "User balance is 0"); //ensures miners that are under dispute cannot vote require(self.stakerDetails[msg.sender].currentStatus != 3, "Miner is under dispute"); //Update user voting status to true disp.voted[msg.sender] = true; //Update the number of votes for the dispute disp.disputeUintVars[keccak256("numberOfVotes")] += 1; //If the user supports the dispute increase the tally for the dispute by the voteWeight //otherwise decrease it if (_supportsDispute) { disp.tally = disp.tally.add(int256(voteWeight)); } else { disp.tally = disp.tally.sub(int256(voteWeight)); } //Let the network know the user has voted on the dispute and their casted vote emit Voted(_disputeId, _supportsDispute, msg.sender, voteWeight); } /** * @dev tallies the votes and locks the stake disbursement(currentStatus = 4) if the vote passes * @param _disputeId is the dispute id */ function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; //Ensure this has not already been executed/tallied require(disp.executed == false, "Dispute has been already executed"); require(now >= disp.disputeUintVars[keccak256("minExecutionDate")], "Time for voting haven't elapsed"); require(disp.reportingParty != address(0), "reporting Party is address 0"); int256 _tally = disp.tally; if (_tally > 0) { //Set the dispute state to passed/true disp.disputeVotePassed = true; } //If the vote is not a proposed fork if (disp.isPropFork == false) { //Ensure the time for voting has elapsed TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; //If the vote for disputing a value is succesful(disp.tally >0) then unstake the reported // miner and transfer the stakeAmount and dispute fee to the reporting party if(stakes.currentStatus == 3){ stakes.currentStatus = 4; } } else if (uint(_tally) >= ((self.uintVars[keccak256("total_supply")] * 10) / 100)) { emit NewTellorAddress(disp.proposedForkAddress); } disp.disputeUintVars[keccak256("tallyDate")] = now; disp.executed = true; emit DisputeVoteTallied(_disputeId, _tally, disp.reportedMiner, disp.reportingParty, disp.disputeVotePassed); } /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(TellorStorage.TellorStorageStruct storage self, address _propNewTellorAddress) public { bytes32 _hash = keccak256(abi.encode(_propNewTellorAddress)); TellorTransfer.doTransfer(self, msg.sender, address(this), 100e18); //This is the fork fee (just 100 tokens flat, no refunds) self.uintVars[keccak256("disputeCount")]++; uint256 disputeId = self.uintVars[keccak256("disputeCount")]; if(self.disputeIdByDisputeHash[_hash] != 0){ self.disputesById[disputeId].disputeUintVars[keccak256("origID")] = self.disputeIdByDisputeHash[_hash]; } else{ self.disputeIdByDisputeHash[_hash] = disputeId; } uint256 origID = self.disputeIdByDisputeHash[_hash]; self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]++; uint256 dispRounds = self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]; self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds))] = disputeId; if(disputeId != origID){ uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds-1))]; require(self.disputesById[lastID].disputeUintVars[keccak256("minExecutionDate")] <= now, "Dispute is already open"); if(self.disputesById[lastID].executed){ require(now - self.disputesById[lastID].disputeUintVars[keccak256("tallyDate")] <= 1 days, "Time for voting haven't elapsed"); } } self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, isPropFork: true, reportedMiner: msg.sender, reportingParty: msg.sender, proposedForkAddress: _propNewTellorAddress, executed: false, disputeVotePassed: false, tally: 0 }); self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days; } /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 origID = self.disputeIdByDisputeHash[_hash]; uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]))]; TellorStorage.Dispute storage disp = self.disputesById[lastID]; require(disp.disputeVotePassed == true, "vote needs to pass"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting for further disputes has not passed"); self.addressVars[keccak256("tellorContract")] = disp.proposedForkAddress; } /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { uint256 origID = self.disputeIdByDisputeHash[self.disputesById[_disputeId].hash]; uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]))]; if(lastID == 0){ lastID = origID; } TellorStorage.Dispute storage disp = self.disputesById[origID]; TellorStorage.Dispute storage last = self.disputesById[lastID]; //disputeRounds is increased by 1 so that the _id is not a negative number when it is the first time a dispute is initiated uint256 dispRounds = disp.disputeUintVars[keccak256("disputeRounds")]; if(dispRounds == 0){ dispRounds = 1; } uint256 _id; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - last.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (last.disputeVotePassed == true){ //Changing the currentStatus and startDate unstakes the reported miner and transfers the stakeAmount stakes.startDate = now - (now % 86400); //Reduce the staker count self.uintVars[keccak256("stakerCount")] -= 1; //Update the minimum dispute fee that is based on the number of stakers updateMinDisputeFee(self); //Decreases the stakerCount since the miner's stake is being slashed if(stakes.currentStatus == 4){ stakes.currentStatus = 5; TellorTransfer.doTransfer(self,disp.reportedMiner,disp.reportingParty,self.uintVars[keccak256("stakeAmount")]); stakes.currentStatus =0 ; } for(uint i = 0; i < dispRounds;i++){ _id = disp.disputeUintVars[keccak256(abi.encode(dispRounds-i))]; if(_id == 0){ _id = origID; } TellorStorage.Dispute storage disp2 = self.disputesById[_id]; //transfer fee adjusted based on number of miners if the minerIndex is not 2(official value) TellorTransfer.doTransfer(self,address(this), disp2.reportingParty, disp2.disputeUintVars[keccak256("fee")]); } } else { stakes.currentStatus = 1; TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { //note we still don't put timestamp back into array (is this an issue? (shouldn't be)) _request.finalValues[disp.disputeUintVars[keccak256("timestamp")]] = disp.disputeUintVars[keccak256("value")]; } if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) { _request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false; } for(uint i = 0; i < dispRounds;i++){ _id = disp.disputeUintVars[keccak256(abi.encode(dispRounds-i))]; if(_id != 0){ last = self.disputesById[_id];//handling if happens during an upgrade } TellorTransfer.doTransfer(self,address(this),last.reportedMiner,self.disputesById[_id].disputeUintVars[keccak256("fee")]); } } if (disp.disputeUintVars[keccak256("minerSlot")] == 2) { self.requestDetails[disp.disputeUintVars[keccak256("requestId")]].apiUintVars[keccak256("disputeCount")]--; } } /** * @dev This function upates the minimun dispute fee as a function of the amount * of staked miners */ function updateMinDisputeFee(TellorStorage.TellorStorageStruct storage self) public { uint256 stakeAmount = self.uintVars[keccak256("stakeAmount")]; uint256 targetMiners = self.uintVars[keccak256("targetMiners")]; self.uintVars[keccak256("disputeFee")] = SafeMath.max(15e18, (stakeAmount-(stakeAmount*(SafeMath.min(targetMiners,self.uintVars[keccak256("stakerCount")])*1000)/ targetMiners)/1000)); } } pragma solidity ^0.5.16; //Functions for retrieving min and Max in 51 length array (requestQ) //Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol library Utilities { /** * @dev Returns the max value in an array. * The zero position here is ignored. It's because * there's no null in solidity and we map each address * to an index in this array. So when we get 51 parties, * and one person is kicked out of the top 50, we * assign them a 0, and when you get mined and pulled * out of the top 50, also a 0. So then lot's of parties * will have zero as the index so we made the array run * from 1-51 with zero as nothing. * @param data is the array to calculate max from * @return max amount and its index within the array */ function getMax(uint256[51] memory data) internal pure returns (uint256 max, uint256 maxIndex) { maxIndex = 1; max = data[maxIndex]; for (uint256 i = 2; i < data.length; i++) { if (data[i] > max) { max = data[i]; maxIndex = i; } } } /** * @dev Returns the minimum value in an array. * @param data is the array to calculate min from * @return min amount and its index within the array */ function getMin(uint256[51] memory data) internal pure returns (uint256 min, uint256 minIndex) { minIndex = data.length - 1; min = data[minIndex]; for (uint256 i = data.length - 2; i > 0; i--) { if (data[i] < min) { min = data[i]; minIndex = i; } } } /** * @dev Returns the 5 requestsId's with the top payouts in an array. * @param data is the array to get the top 5 from * @return to 5 max amounts and their respective index within the array */ function getMax5(uint256[51] memory data) internal pure returns (uint256[5] memory max, uint256[5] memory maxIndex) { uint256 min5 = data[1]; uint256 minI = 0; for(uint256 j=0;j<5;j++){ max[j]= data[j+1];//max[0]=data[1] maxIndex[j] = j+1;//maxIndex[0]= 1 if(max[j] < min5){ min5 = max[j]; minI = j; } } for(uint256 i = 6; i < data.length; i++) { if (data[i] > min5) { max[minI] = data[i]; maxIndex[minI] = i; min5 = data[i]; for(uint256 j=0;j<5;j++){ if(max[j] < min5){ min5 = max[j]; minI = j; } } } } } } pragma solidity ^0.5.16; /** * itle Tellor Stake * @dev Contains the methods related to miners staking and unstaking. Tellor.sol * references this library for function's logic. */ library TellorStake { event NewStake(address indexed _sender); //Emits upon new staker event StakeWithdrawn(address indexed _sender); //Emits when a staker is now no longer staked event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period /*Functions*/ /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the deposit */ function requestStakingWithdraw(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require that the miner is staked require(stakes.currentStatus == 1, "Miner is not staked"); //Change the miner staked to locked to be withdrawStake stakes.currentStatus = 2; //Change the startDate to now since the lock up period begins now //and the miner can only withdraw 7 days later from now(check the withdraw function) stakes.startDate = now - (now % 86400); //Reduce the staker count self.uintVars[keccak256("stakerCount")] -= 1; //Update the minimum dispute fee that is based on the number of stakers TellorDispute.updateMinDisputeFee(self); emit StakeWithdrawRequested(msg.sender); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have //passed by since they locked for withdraw require(now - (now % 86400) - stakes.startDate >= 7 days, "7 days didn't pass"); require(stakes.currentStatus == 2, "Miner was not locked for withdrawal"); stakes.currentStatus = 0; emit StakeWithdrawn(msg.sender); } /** * @dev This function allows miners to deposit their stake. */ function depositStake(TellorStorage.TellorStorageStruct storage self) public { newStake(self, msg.sender); //self adjusting disputeFee TellorDispute.updateMinDisputeFee(self); } /** * @dev This function is used by the init function to succesfully stake the initial 5 miners. * The function updates their status/state and status start date so they are locked it so they can't withdraw * and updates the number of stakers in the system. */ function newStake(TellorStorage.TellorStorageStruct storage self, address staker) internal { require(TellorTransfer.balanceOf(self, staker) >= self.uintVars[keccak256("stakeAmount")], "Balance is lower than stake amount"); //Ensure they can only stake if they are not currrently staked or if their stake time frame has ended //and they are currently locked for witdhraw require(self.stakerDetails[staker].currentStatus == 0 || self.stakerDetails[staker].currentStatus == 2, "Miner is in the wrong state"); self.uintVars[keccak256("stakerCount")] += 1; self.stakerDetails[staker] = TellorStorage.StakeInfo({ currentStatus: 1, //this resets their stake start date to today startDate: now - (now % 86400) }); emit NewStake(staker); } /** * @dev Getter function for the requestId being mined * @return variables for the current minin event: Challenge, 5 RequestId, difficulty and Totaltips */ function getNewCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns(bytes32 _challenge,uint[5] memory _requestIds,uint256 _difficulty, uint256 _tip){ for(uint i=0;i<5;i++){ _requestIds[i] = self.currentMiners[i].value; } return (self.currentChallenge,_requestIds,self.uintVars[keccak256("difficulty")],self.uintVars[keccak256("currentTotalTips")]); } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on top 5 requests(highest payout)-- RequestId, Totaltips */ function getNewVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck) { idsOnDeck = getTopRequestIDs(self); for(uint i = 0;i<5;i++){ tipsOnDeck[i] = self.requestDetails[idsOnDeck[i]].apiUintVars[keccak256("totalTip")]; } } /** * @dev Getter function for the top 5 requests with highest payouts. This function is used within the getNewVariablesOnDeck function * @return uint256[5] is an array with the top 5(highest payout) _requestIds at the time the function is called */ function getTopRequestIDs(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[5] memory _requestIds) { uint256[5] memory _max; uint256[5] memory _index; (_max, _index) = Utilities.getMax5(self.requestQ); for(uint i=0;i<5;i++){ if(_max[i] != 0){ _requestIds[i] = self.requestIdByRequestQIndex[_index[i]]; } else{ _requestIds[i] = self.currentMiners[4-i].value; } } } } pragma solidity ^0.5.0; /** * @title Tellor Getters Library * @dev This is the getter library for all variables in the Tellor Tributes system. TellorGetters references this * libary for the getters logic */ library TellorGettersLibrary { using SafeMath for uint256; event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ //The next two functions are onlyOwner functions. For Tellor to be truly decentralized, we will need to transfer the Deity to the 0 address. //Only needs to be in library /** * @dev This function allows us to set a new Deity (or remove it) * @param _newDeity address of the new Deity of the tellor system */ function changeDeity(TellorStorage.TellorStorageStruct storage self, address _newDeity) internal { require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity"); self.addressVars[keccak256("_deity")] = _newDeity; } //Only needs to be in library /** * @dev This function allows the deity to upgrade the Tellor System * @param _tellorContract address of new updated TellorCore contract */ function changeTellorContract(TellorStorage.TellorStorageStruct storage self, address _tellorContract) internal { require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity"); self.addressVars[keccak256("tellorContract")] = _tellorContract; emit NewTellorAddress(_tellorContract); } /*Tellor Getters*/ /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge, address _miner) public view returns (bool) { return self.minersByChallenge[_challenge][_miner]; } /** * @dev Checks if an address voted in a dispute * @param _disputeId to look up * @param _address of voting party to look up * @return bool of whether or not party voted */ function didVote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, address _address) internal view returns (bool) { return self.disputesById[_disputeId].voted[_address]; } /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * @return address requested */ function getAddressVars(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (address) { return self.addressVars[_data]; } /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * @return uint of requestId * @return uint of timestamp * @return uint of value * @return uint of minExecutionDate * @return uint of numberOfVotes * @return uint of blocknumber * @return uint of minerSlot * @return uint of quorum * @return uint of fee * @return int count of the current tally */ function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) internal view returns (bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256) { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; return ( disp.hash, disp.executed, disp.disputeVotePassed, disp.isPropFork, disp.reportedMiner, disp.reportingParty, disp.proposedForkAddress, [ disp.disputeUintVars[keccak256("requestId")], disp.disputeUintVars[keccak256("timestamp")], disp.disputeUintVars[keccak256("value")], disp.disputeUintVars[keccak256("minExecutionDate")], disp.disputeUintVars[keccak256("numberOfVotes")], disp.disputeUintVars[keccak256("blockNumber")], disp.disputeUintVars[keccak256("minerSlot")], disp.disputeUintVars[keccak256("quorum")], disp.disputeUintVars[keccak256("fee")] ], disp.tally ); } /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns (bytes32, uint256, uint256, string memory, uint256, uint256) { return ( self.currentChallenge, self.uintVars[keccak256("currentRequestId")], self.uintVars[keccak256("difficulty")], self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString, self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")], self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")] ); } /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(TellorStorage.TellorStorageStruct storage self, bytes32 _hash) internal view returns (uint256) { return self.disputeIdByDisputeHash[_hash]; } /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bytes32 _data) internal view returns (uint256) { return self.disputesById[_disputeId].disputeUintVars[_data]; } /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, bool) { return ( retrieveData( self, self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]], self.uintVars[keccak256("timeOfLastNewValue")] ), true ); } /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256, bool) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; if (_request.requestTimestamps.length != 0) { return (retrieveData(self, _requestId, _request.requestTimestamps[_request.requestTimestamps.length - 1]), true); } else { return (0, false); } } /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256) { return self.requestDetails[_requestId].minedBlockNum[_timestamp]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (address[5] memory) { return self.requestDetails[_requestId].minersByValue[_timestamp]; } /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256) { return self.requestDetails[_requestId].requestTimestamps.length; } /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(TellorStorage.TellorStorageStruct storage self, uint256 _index) internal view returns (uint256) { require(_index <= 50, "RequestQ index is above 50"); return self.requestIdByRequestQIndex[_index]; } /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _timestamp) internal view returns (uint256) { return self.requestIdByTimestamp[_timestamp]; } /** * @dev Getter function for requestId based on the qeuaryHash * @param _queryHash hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns (uint256) { return self.requestIdByQueryHash[_queryHash]; } /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[51] memory) { return self.requestQ; } /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, bytes32 _data) internal view returns (uint256) { return self.requestDetails[_requestId].apiUintVars[_data]; } /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (string memory, string memory, bytes32, uint256, uint256, uint256) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; return ( _request.queryString, _request.dataSymbol, _request.queryHash, _request.apiUintVars[keccak256("granularity")], _request.apiUintVars[keccak256("requestQPosition")], _request.apiUintVars[keccak256("totalTip")] ); } /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(TellorStorage.TellorStorageStruct storage self, address _staker) internal view returns (uint256, uint256) { return (self.stakerDetails[_staker].currentStatus, self.stakerDetails[_staker].startDate); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256[5] memory) { return self.requestDetails[_requestId].valuesByTimestamp[_timestamp]; } /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self, uint256 _requestID, uint256 _index) internal view returns (uint256) { return self.requestDetails[_requestID].requestTimestamps[_index]; } /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (uint256) { return self.uintVars[_data]; } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, uint256, string memory) { uint256 newRequestId = getTopRequestID(self); return ( newRequestId, self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")], self.requestDetails[newRequestId].queryString ); } /** * @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function * @return uint _requestId of request with highest payout at the time the function is called */ function getTopRequestID(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256 _requestId) { uint256 _max; uint256 _index; (_max, _index) = Utilities.getMax(self.requestQ); _requestId = self.requestIdByRequestQIndex[_index]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to looku p * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (bool) { return self.requestDetails[_requestId].inDispute[_timestamp]; } /** * @dev Retreive value from oracle based on requestId/timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return uint value for requestId/timestamp submitted */ function retrieveData(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256) { return self.requestDetails[_requestId].finalValues[_timestamp]; } /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256) { return self.uintVars[keccak256("total_supply")]; } } pragma solidity ^0.5.16; /** * @title Tellor Oracle System Library * @dev Contains the functions' logic for the Tellor contract where miners can submit the proof of work * along with the value and smart contracts can requestData and tip miners. */ library TellorLibrary { using SafeMath for uint256; bytes32 public constant requestCount = 0x05de9147d05477c0a5dc675aeea733157f5092f82add148cf39d579cafe3dc98; //keccak256("requestCount") bytes32 public constant totalTip = 0x2a9e355a92978430eca9c1aa3a9ba590094bac282594bccf82de16b83046e2c3; //keccak256("totalTip") bytes32 public constant _tBlock = 0x969ea04b74d02bb4d9e6e8e57236e1b9ca31627139ae9f0e465249932e824502; //keccak256("_tBlock") bytes32 public constant timeOfLastNewValue = 0x97e6eb29f6a85471f7cc9b57f9e4c3deaf398cfc9798673160d7798baf0b13a4; //keccak256("timeOfLastNewValue") bytes32 public constant difficulty = 0xb12aff7664b16cb99339be399b863feecd64d14817be7e1f042f97e3f358e64e; //keccak256("difficulty") bytes32 public constant timeTarget = 0xad16221efc80aaf1b7e69bd3ecb61ba5ffa539adf129c3b4ffff769c9b5bbc33; //keccak256("timeTarget") bytes32 public constant runningTips = 0xdb21f0c4accc4f2f5f1045353763a9ffe7091ceaf0fcceb5831858d96cf84631; //keccak256("runningTips") bytes32 public constant currentReward = 0x9b6853911475b07474368644a0d922ee13bc76a15cd3e97d3e334326424a47d4; //keccak256("currentReward") bytes32 public constant total_supply = 0xb1557182e4359a1f0c6301278e8f5b35a776ab58d39892581e357578fb287836; //keccak256("total_supply") bytes32 public constant devShare = 0x8fe9ded8d7c08f720cf0340699024f83522ea66b2bbfb8f557851cb9ee63b54c; //keccak256("devShare") bytes32 public constant _owner = 0x9dbc393ddc18fd27b1d9b1b129059925688d2f2d5818a5ec3ebb750b7c286ea6; //keccak256("_owner") bytes32 public constant requestQPosition = 0x1e344bd070f05f1c5b3f0b1266f4f20d837a0a8190a3a2da8b0375eac2ba86ea; //keccak256("requestQPosition") bytes32 public constant currentTotalTips = 0xd26d9834adf5a73309c4974bf654850bb699df8505e70d4cfde365c417b19dfc; //keccak256("currentTotalTips") bytes32 public constant slotProgress =0x6c505cb2db6644f57b42d87bd9407b0f66788b07d0617a2bc1356a0e69e66f9a; //keccak256("slotProgress") bytes32 public constant pending_owner = 0x44b2657a0f8a90ed8e62f4c4cceca06eacaa9b4b25751ae1ebca9280a70abd68; //keccak256("pending_owner") bytes32 public constant currentRequestId = 0x7584d7d8701714da9c117f5bf30af73b0b88aca5338a84a21eb28de2fe0d93b8; //keccak256("currentRequestId") event TipAdded(address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips); //emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system) event NewChallenge( bytes32 indexed _currentChallenge, uint256[5] _currentRequestId, uint256 _difficulty, uint256 _totalTips ); //Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined event NewValue(uint256[5] _requestId, uint256 _time, uint256[5] _value, uint256 _totalTips, bytes32 indexed _currentChallenge); //Emits upon each mine (5 total) and shows the miner, nonce, and value submitted event NonceSubmitted(address indexed _miner, string _nonce, uint256[5] _requestId, uint256[5] _value, bytes32 indexed _currentChallenge); event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner); event OwnershipProposed(address indexed _previousOwner, address indexed _newOwner); /*Functions*/ /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { require(_requestId != 0, "RequestId is 0"); require(_tip != 0, "Tip should be greater than 0"); uint256 _count =self.uintVars[requestCount] + 1; if(_requestId == _count){ self.uintVars[requestCount] = _count; } else{ require(_requestId < _count, "RequestId is not less than count"); } TellorTransfer.doTransfer(self, msg.sender, address(this), _tip); //Update the information for the request that should be mined next based on the tip submitted updateOnDeck(self, _requestId, _tip); emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[totalTip]); } /** * @dev This function is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first * 5 values received, pays the miners, the dev share and assigns a new challenge * @param _nonce or solution for the PoW for the requestId * @param _requestId for the current request being mined */ function newBlock(TellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256[5] memory _requestId) public { TellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[_tBlock]]; // If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge //difficulty up or donw by the difference between the target time and how long it took to solve the previous challenge //otherwise it sets it to 1 uint timeDiff = now - self.uintVars[timeOfLastNewValue]; int256 _change = int256(SafeMath.min(1200, timeDiff)); int256 _diff = int256(self.uintVars[difficulty]); _change = (_diff * (int256(self.uintVars[timeTarget]) - _change)) / 4000; if (_change == 0) { _change = 1; } self.uintVars[difficulty] = uint256(SafeMath.max(_diff + _change,1)); //Sets time of value submission rounded to 1 minute bytes32 _currChallenge = self.currentChallenge; uint256 _timeOfLastNewValue = now - (now % 1 minutes); self.uintVars[timeOfLastNewValue] = _timeOfLastNewValue; uint[5] memory a; for (uint k = 0; k < 5; k++) { for (uint i = 1; i < 5; i++) { uint256 temp = _tblock.valuesByTimestamp[k][i]; address temp2 = _tblock.minersByValue[k][i]; uint256 j = i; while (j > 0 && temp < _tblock.valuesByTimestamp[k][j - 1]) { _tblock.valuesByTimestamp[k][j] = _tblock.valuesByTimestamp[k][j - 1]; _tblock.minersByValue[k][j] = _tblock.minersByValue[k][j - 1]; j--; } if (j < i) { _tblock.valuesByTimestamp[k][j] = temp; _tblock.minersByValue[k][j] = temp2; } } TellorStorage.Request storage _request = self.requestDetails[_requestId[k]]; //Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number a = _tblock.valuesByTimestamp[k]; _request.finalValues[_timeOfLastNewValue] = a[2]; _request.minersByValue[_timeOfLastNewValue] = _tblock.minersByValue[k]; _request.valuesByTimestamp[_timeOfLastNewValue] = _tblock.valuesByTimestamp[k]; delete _tblock.minersByValue[k]; delete _tblock.valuesByTimestamp[k]; _request.requestTimestamps.push(_timeOfLastNewValue); _request.minedBlockNum[_timeOfLastNewValue] = block.number; _request.apiUintVars[totalTip] = 0; } emit NewValue( _requestId, _timeOfLastNewValue, a, self.uintVars[runningTips], _currChallenge ); //map the timeOfLastValue to the requestId that was just mined self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId[0]; //add timeOfLastValue to the newValueTimestamps array self.newValueTimestamps.push(_timeOfLastNewValue); address[5] memory miners = self.requestDetails[_requestId[0]].minersByValue[_timeOfLastNewValue]; //payMinersRewards _payReward(self, timeDiff, miners); self.uintVars[_tBlock] ++; uint256[5] memory _topId = TellorStake.getTopRequestIDs(self); for(uint i = 0; i< 5;i++){ self.currentMiners[i].value = _topId[i]; self.requestQ[self.requestDetails[_topId[i]].apiUintVars[requestQPosition]] = 0; self.uintVars[currentTotalTips] += self.requestDetails[_topId[i]].apiUintVars[totalTip]; } //Issue the the next challenge _currChallenge = keccak256(abi.encode(_nonce, _currChallenge, blockhash(block.number - 1))); self.currentChallenge = _currChallenge; // Save hash for next proof emit NewChallenge( _currChallenge, _topId, self.uintVars[difficulty], self.uintVars[currentTotalTips] ); } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string calldata _nonce,uint256[5] calldata _requestId, uint256[5] calldata _value) external { _verifyNonce(self, _nonce); _submitMiningSolution(self, _nonce, _requestId, _value); } function _submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string memory _nonce,uint256[5] memory _requestId, uint256[5] memory _value) internal { //Verifying Miner Eligibility bytes32 _hashMsgSender = keccak256(abi.encode(msg.sender)); require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker"); require(now - self.uintVars[_hashMsgSender] > 15 minutes, "Miner can only win rewards once per 15 min"); require(_requestId[0] == self.currentMiners[0].value,"Request ID is wrong"); require(_requestId[1] == self.currentMiners[1].value,"Request ID is wrong"); require(_requestId[2] == self.currentMiners[2].value,"Request ID is wrong"); require(_requestId[3] == self.currentMiners[3].value,"Request ID is wrong"); require(_requestId[4] == self.currentMiners[4].value,"Request ID is wrong"); self.uintVars[_hashMsgSender] = now; bytes32 _currChallenge = self.currentChallenge; uint256 _slotProgress = self.uintVars[slotProgress]; //Saving the challenge information as unique by using the msg.sender //Checking and updating Miner Status require(self.minersByChallenge[_currChallenge][msg.sender] == false, "Miner already submitted the value"); //Update the miner status to true once they submit a value so they don't submit more than once self.minersByChallenge[_currChallenge][msg.sender] = true; //Updating Request TellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[_tBlock]]; _tblock.minersByValue[1][_slotProgress]= msg.sender; //Assigng directly is cheaper than using a for loop _tblock.valuesByTimestamp[0][_slotProgress] = _value[0]; _tblock.valuesByTimestamp[1][_slotProgress] = _value[1]; _tblock.valuesByTimestamp[2][_slotProgress] = _value[2]; _tblock.valuesByTimestamp[3][_slotProgress] = _value[3]; _tblock.valuesByTimestamp[4][_slotProgress] = _value[4]; _tblock.minersByValue[0][_slotProgress]= msg.sender; _tblock.minersByValue[1][_slotProgress]= msg.sender; _tblock.minersByValue[2][_slotProgress]= msg.sender; _tblock.minersByValue[3][_slotProgress]= msg.sender; _tblock.minersByValue[4][_slotProgress]= msg.sender; //If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received if (_slotProgress + 1 == 5) { //slotProgress has been incremented, but we're using the variable on stack to save gas newBlock(self, _nonce, _requestId); self.uintVars[slotProgress] = 0; } else{ self.uintVars[slotProgress]++; } emit NonceSubmitted(msg.sender, _nonce, _requestId, _value, _currChallenge); } function _verifyNonce(TellorStorage.TellorStorageStruct storage self,string memory _nonce ) view internal { require(uint256( sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce)))))) ) % self.uintVars[difficulty] == 0 || (now - (now % 1 minutes)) - self.uintVars[timeOfLastNewValue] >= 15 minutes, "Incorrect nonce for current challenge" ); } /** * @dev Internal function to calculate and pay rewards to miners * */ function _payReward(TellorStorage.TellorStorageStruct storage self, uint _timeDiff, address[5] memory miners) internal { //_timeDiff is how many minutes passed since last block uint _currReward = 1e18; uint reward = _timeDiff* _currReward / 300; //each miner get's uint _tip = self.uintVars[currentTotalTips] / 10; uint _devShare = reward / 2; TellorTransfer.doTransfer(self, address(this), miners[0], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[1], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[2], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[3], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[4], reward + _tip); //update the total supply self.uintVars[total_supply] += _devShare + reward * 5 - (self.uintVars[currentTotalTips] / 2); TellorTransfer.doTransfer(self, address(this), self.addressVars[_owner], _devShare); self.uintVars[currentTotalTips] = 0; } /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(TellorStorage.TellorStorageStruct storage self, address payable _pendingOwner) public { require(msg.sender == self.addressVars[_owner], "Sender is not owner"); emit OwnershipProposed(self.addressVars[_owner], _pendingOwner); self.addressVars[pending_owner] = _pendingOwner; } /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership(TellorStorage.TellorStorageStruct storage self) public { require(msg.sender == self.addressVars[pending_owner], "Sender is not pending owner"); emit OwnershipTransferred(self.addressVars[_owner], self.addressVars[pending_owner]); self.addressVars[_owner] = self.addressVars[pending_owner]; } /** * @dev This function updates APIonQ and the requestQ when requestData or addTip are ran * @param _requestId being requested * @param _tip is the tip to add */ function updateOnDeck(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { TellorStorage.Request storage _request = self.requestDetails[_requestId]; _request.apiUintVars[totalTip] = _request.apiUintVars[totalTip].add(_tip); if(self.currentMiners[0].value == _requestId || self.currentMiners[1].value== _requestId ||self.currentMiners[2].value == _requestId||self.currentMiners[3].value== _requestId || self.currentMiners[4].value== _requestId ){ self.uintVars[currentTotalTips] += _tip; } else { //if the request is not part of the requestQ[51] array //then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array if (_request.apiUintVars[requestQPosition] == 0) { uint256 _min; uint256 _index; (_min, _index) = Utilities.getMin(self.requestQ); //we have to zero out the oldOne //if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero //then add it to the requestQ array aand map its index information to the requestId and the apiUintvars if (_request.apiUintVars[totalTip] > _min || _min == 0) { self.requestQ[_index] = _request.apiUintVars[totalTip]; self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[requestQPosition] = 0; self.requestIdByRequestQIndex[_index] = _requestId; _request.apiUintVars[requestQPosition] = _index; } // else if the requestid is part of the requestQ[51] then update the tip for it } else{ self.requestQ[_request.apiUintVars[requestQPosition]] += _tip; } } } } pragma solidity ^0.5.16; /** * @title Tellor Oracle System * @dev Oracle contract where miners can submit the proof of work along with the value. * The logic for this contract is in TellorLibrary.sol, TellorDispute.sol, TellorStake.sol, * and TellorTransfer.sol */ contract Tellor { using SafeMath for uint256; using TellorDispute for TellorStorage.TellorStorageStruct; using TellorLibrary for TellorStorage.TellorStorageStruct; using TellorStake for TellorStorage.TellorStorageStruct; using TellorTransfer for TellorStorage.TellorStorageStruct; TellorStorage.TellorStorageStruct tellor; /*Functions*/ /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute(uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) external { tellor.beginDispute(_requestId, _timestamp, _minerIndex); } /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external { tellor.vote(_disputeId, _supportsDispute); } /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external { tellor.tallyVotes(_disputeId); } /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external { tellor.proposeFork(_propNewTellorAddress); } /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external { tellor.addTip(_requestId, _tip); } /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution(string calldata _nonce,uint256[5] calldata _requestId, uint256[5] calldata _value) external { tellor.submitMiningSolution(_nonce,_requestId, _value); } /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external { tellor.proposeOwnership(_pendingOwner); } /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external { tellor.claimOwnership(); } /** * @dev This function allows miners to deposit their stake. */ function depositStake() external { tellor.depositStake(); } /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external { tellor.requestStakingWithdraw(); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external { tellor.withdrawStake(); } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool) { return tellor.approve(_spender, _amount); } /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool) { return tellor.transfer(_to, _amount); } /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(address _from, address _to, uint256 _amount) external returns (bool) { return tellor.transferFrom(_from, _to, _amount); } /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory) { return "Tellor Tributes"; } /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory) { return "TRB"; } /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8) { return 18; } /** * @dev Getter for the current variables that include the 5 requests Id's * @return the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns(bytes32 _challenge,uint[5] memory _requestIds,uint256 _difficutly, uint256 _tip){ return tellor.getNewCurrentVariables(); } /** * @dev Getter for the top tipped 5 requests Id's * @return the 5 requestsId */ function getTopRequestIDs() external view returns(uint256[5] memory _requestIds){ return tellor.getTopRequestIDs(); } /** * @dev Getter for the 5 requests Id's next in line to get mined * @return the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck) { return tellor.getNewVariablesOnDeck(); } /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint _disputeId) external{ return tellor.updateTellor(_disputeId); } /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee (uint _disputeId) external{ return tellor.unlockDisputeFee(_disputeId); } /*******************TEST Functions NOT INCLUDED ON PRODUCTION/MAINNET/RINKEBY******/ // /*This is a cheat for demo purposes, will delete upon actual launch*/ // function theLazyCoon(address _address, uint _amount) external { // tellor.theLazyCoon(_address,_amount); // } // // function testSubmitMiningSolution(string calldata _nonce, uint256 _requestId, uint256 _value) external { // // tellor.testSubmitMiningSolution(_nonce, _requestId, _value); // // } // function testSubmitMiningSolution(string calldata _nonce,uint256[5] calldata _requestId, uint256[5] calldata _value) external { // tellor.testSubmitMiningSolution(_nonce,_requestId, _value); // } /***************END TEST Functions NOT INCLUDED ON PRODUCTION/MAINNET/RINKEBY******/ }
keccak256("requestQPosition")
bytes32 public constant requestQPosition = 0x1e344bd070f05f1c5b3f0b1266f4f20d837a0a8190a3a2da8b0375eac2ba86ea;
1,434,186
[ 1, 79, 24410, 581, 5034, 2932, 2293, 53, 2555, 7923, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1731, 1578, 1071, 5381, 590, 53, 2555, 273, 374, 92, 21, 73, 5026, 24, 16410, 20, 7301, 74, 6260, 74, 21, 71, 25, 70, 23, 74, 20, 70, 2138, 6028, 74, 24, 74, 3462, 72, 28, 6418, 69, 20, 69, 28, 30454, 69, 23, 69, 22, 2414, 28, 70, 4630, 5877, 73, 1077, 22, 12124, 5292, 24852, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0x0475C9B2D168167aA161EC2a617712Bf7045300f/sources/MultiCheck.sol
get current eth value
uint256 contractETHBalance = address(this).balance;
3,793,332
[ 1, 588, 783, 13750, 460, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 7734, 2254, 5034, 6835, 1584, 44, 13937, 273, 1758, 12, 2211, 2934, 12296, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.19; // The frontend for this smart contract is a dApp hosted at // https://hire.kohweijie.com /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @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&#39;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; } } // The frontend for this smart contract is a dApp hosted at // https://hire.kohweijie.com contract HireMe is Ownable { struct Bid { // Data structure representing an individual bid bool exists; // 0. Whether the bid exists uint id; // 1. The ID of the bid. uint timestamp; // 2. The timestamp of when the bid was made address bidder; // 3. The address of the bidder uint amount; // 4. The amount of ETH in the bid string email; // 5. The bidder&#39;s email address string organisation; // 6. The bidder&#39;s organisation } event BidMade(uint indexed id, address indexed bidder, uint indexed amount); event Reclaimed(address indexed bidder, uint indexed amount); event Donated(uint indexed amount); Bid[] public bids; // Array of all bids uint[] public bidIds; // Array of all bid IDs // Constants which govern the bid prices and auction duration uint private constant MIN_BID = 1 ether; uint private constant BID_STEP = 0.01 ether; uint private constant INITIAL_BIDS = 4; uint private constant EXPIRY_DAYS_BEFORE = 7 days; uint private constant EXPIRY_DAYS_AFTER = 3 days; // For development only //uint private constant EXPIRY_DAYS_BEFORE = 10 minutes; //uint private constant EXPIRY_DAYS_AFTER = 10 minutes; // SHA256 checksum of https://github.com/weijiekoh/hireme/blob/master/AUTHOR.asc // See the bottom of this file for the contents of AUTHOR.asc string public constant AUTHORSIGHASH = "8c8b82a2d83a33cb0f45f5f6b22b45c1955f08fc54e7ab4d9e76fb76843c4918"; // Whether the donate() function has been called bool public donated = false; // Whether the manuallyEndAuction() function has been called bool public manuallyEnded = false; // Tracks the total amount of ETH currently residing in the contract // balance per address. mapping (address => uint) public addressBalance; // The Internet Archive&#39;s ETH donation address address public charityAddress = 0x635599b0ab4b5c6B1392e0a2D1d69cF7d1ddDF02; // Only the contract owner may end this contract, and may do so only if // there are 0 bids. function manuallyEndAuction () public onlyOwner { require(manuallyEnded == false); require(bids.length == 0); manuallyEnded = true; } // Place a bid. function bid(string _email, string _organisation) public payable { address _bidder = msg.sender; uint _amount = msg.value; uint _id = bids.length; // The auction must not be over require(!hasExpired() && !manuallyEnded); // The bidder must be neither the contract owner nor the charity // donation address require(_bidder != owner && _bidder != charityAddress); // The bidder address, email, and organisation must valid require(_bidder != address(0)); require(bytes(_email).length > 0); require(bytes(_organisation).length > 0); // Make sure the amount bid is more than the rolling minimum bid require(_amount >= calcCurrentMinBid()); // Update the state with the new bid bids.push(Bid(true, _id, now, _bidder, _amount, _email, _organisation)); bidIds.push(_id); // Add to, not replace, the state variable which tracks the total // amount paid per address, because a bidder may make multiple bids addressBalance[_bidder] = SafeMath.add(addressBalance[_bidder], _amount); // Emit the event BidMade(_id, _bidder, _amount); } function reclaim () public { address _caller = msg.sender; uint _amount = calcAmtReclaimable(_caller); // There must be at least 2 bids. Note that if there is only 1 bid and // that bid is the winning bid, it cannot be reclaimed. require(bids.length >= 2); // The auction must not have been manually ended require(!manuallyEnded); // Make sure the amount to reclaim is more than 0 require(_amount > 0); // Subtract the amount to be reclaimed from the state variable which // tracks the total amount paid per address uint _newTotal = SafeMath.sub(addressBalance[_caller], _amount); // The amount must not be negative, or the contract is buggy assert(_newTotal >= 0); // Update the state to prevent double-spending addressBalance[_caller] = _newTotal; // Make the transfer _caller.transfer(_amount); // Emit the event Reclaimed(_caller, _amount); } function donate () public { // donate() can only be called once assert(donated == false); // Only the contract owner or the charity address may send the funds to // charityAddress require(msg.sender == owner || msg.sender == charityAddress); // The auction must be over require(hasExpired()); // If the auction has been manually ended at this point, the contract // is buggy assert(!manuallyEnded); // There must be at least 1 bid, or the contract is buggy assert(bids.length > 0); // Calculate the amount to donate uint _amount; if (bids.length == 1) { // If there is only 1 bid, transfer that amount _amount = bids[0].amount; } else { // If there is more than 1 bid, transfer the second highest bid _amount = bids[SafeMath.sub(bids.length, 2)].amount; } // The amount to be donated must be more than 0, or this contract is // buggy assert(_amount > 0); // Prevent double-donating donated = true; // Transfer the winning bid amount to charity charityAddress.transfer(_amount); Donated(_amount); } function calcCurrentMinBid () public view returns (uint) { if (bids.length == 0) { return MIN_BID; } else { uint _lastBidId = SafeMath.sub(bids.length, 1); uint _lastBidAmt = bids[_lastBidId].amount; return SafeMath.add(_lastBidAmt, BID_STEP); } } function calcAmtReclaimable (address _bidder) public view returns (uint) { // This function calculates the amount that _bidder can get back. // A. if the auction is over, and _bidder is the winner, they should // get back the total amount bid minus the second highest bid. // B. if the auction is not over, and _bidder is not the current // winner, they should get back the total they had bid // C. if the auction is ongoing, and _bidder is the current winner, // they should get back the total amount they had bid minus the top // bid. // D. if the auction is ongoing, and _bidder is not the current winner, // they should get back the total amount they had bid. uint _totalAmt = addressBalance[_bidder]; if (bids.length == 0) { return 0; } if (bids[SafeMath.sub(bids.length, 1)].bidder == _bidder) { // If the bidder is the current winner if (hasExpired()) { // scenario A uint _secondPrice = bids[SafeMath.sub(bids.length, 2)].amount; return SafeMath.sub(_totalAmt, _secondPrice); } else { // scenario C uint _highestPrice = bids[SafeMath.sub(bids.length, 1)].amount; return SafeMath.sub(_totalAmt, _highestPrice); } } else { // scenarios B and D // If the bidder is not the current winner return _totalAmt; } } function getBidIds () public view returns (uint[]) { return bidIds; } // Calcuate the timestamp after which the auction will expire function expiryTimestamp () public view returns (uint) { uint _numBids = bids.length; // There is no expiry if there are no bids require(_numBids > 0); // The timestamp of the most recent bid uint _lastBidTimestamp = bids[SafeMath.sub(_numBids, 1)].timestamp; if (_numBids <= INITIAL_BIDS) { return SafeMath.add(_lastBidTimestamp, EXPIRY_DAYS_BEFORE); } else { return SafeMath.add(_lastBidTimestamp, EXPIRY_DAYS_AFTER); } } function hasExpired () public view returns (bool) { uint _numBids = bids.length; // The auction cannot expire if there are no bids if (_numBids == 0) { return false; } else { // Compare with the current time return now >= this.expiryTimestamp(); } } } // Contents of AUTHOR.asc and AUTHOR (remove the backslashes which preface each // line) // AUTHOR.asc: //-----BEGIN PGP SIGNATURE----- // //iQIzBAABCAAdBQJak6eBFhxjb250YWN0QGtvaHdlaWppZS5jb20ACgkQkNtDYXzM //FjKytA/+JF75jH+d/9nEitJKRcsrFgadVjMwNjUt1B7IvoZJqpHj9BSHtKhsVEI5 //iME24rgbr3YRXLi7GbQS+Ovyf3Ks7BHCA/t12PWOVm9zRBEswojZIg1UjTqtYboS //0xrnrY8A71g1RX/jN4uCQ9FohRMAPzTTV9Gt6XDpB9Uzk0HBkUOpVHPnqxSerzbp //fSwTCzLgcsTKUJYfeOQMuSwTTXc/btJss82WQpK76xdi5+4hp3tjyZZuY7ruj60N //g9f9pHafsWRujMhmX0G8btjK/7/cJL/KbFFafb3sA7Xes0uoUbs+pQXTvuMBx2g5 //1/BH63aHXdZC2/767JyR18gZN6PnwsZt7i8CowvDcGMni5f0la4O53HCZEGaHYFf //IKnJX4LhEJEezcflqSgxm1y7hlUFqC1T7janL0s4rCxoW7iPgNlii62vSzg0TTwH //9L6v8aYwWgAwfma2o3XWMCjA/K/BIfWd2w+1ex/gvTVCefOxz1zEPdjhWh89fopb //ydxV4fllXLXoB2wmv305E4eryq4lX40w9WxO7Dxq3yU+fmK8BaXLsjUf4fT9AU1m //VEo3ndjFXkSELwqTQalxod41j4rYxS6SyxOj6R3/3ejbJIL0kzwKuDlZIkj8Xsfx //o2b+QtKANMwC2KRZQBnNdnF2XVOCEFW1XZykWPW6FR1iYS6WEJ0= //=J3JJ //-----END PGP SIGNATURE----- // AUTHOR: //Koh Wei Jie <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3a0acadb7a2a0b783a8acabb4a6aaa9aaa6eda0acae">[email&#160;protected]</a>>
Transfer the winning bid amount to charity
charityAddress.transfer(_amount);
10,624,763
[ 1, 5912, 326, 5657, 2093, 9949, 3844, 358, 1149, 560, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1149, 560, 1887, 18, 13866, 24899, 8949, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0x73d835325637FAF11Ae1838428510D9566E1a465/sources/contracts/strategies/FrostStrategyForSA.sol
* @notice Strategy for Frost/
contract FrostStrategyForSA is YakStrategy { using SafeMath for uint; IFrostChef public stakingContract; IPair private swapPairToken; IPair private swapPairWAVAXTundra; address private constant WAVAX = 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7; uint public PID; constructor( string memory _name, address _depositToken, address _rewardToken, address _stakingContract, address _swapPairWAVAXTundra, address _swapPairToken, address _timelock, uint _pid, uint _minTokensToReinvest, uint _adminFeeBips, uint _devFeeBips, uint _reinvestRewardBips pragma solidity ^0.7.0; ) { name = _name; depositToken = IPair(_depositToken); rewardToken = IERC20(_rewardToken); stakingContract = IFrostChef(_stakingContract); swapPairWAVAXTundra = IPair(_swapPairWAVAXTundra); swapPairToken = IPair(_swapPairToken); PID = _pid; devAddr = msg.sender; setAllowances(); updateMinTokensToReinvest(_minTokensToReinvest); updateAdminFee(_adminFeeBips); updateDevFee(_devFeeBips); updateReinvestReward(_reinvestRewardBips); updateDepositsEnabled(true); transferOwnership(_timelock); emit Reinvest(0, 0); } function setAllowances() public override onlyOwner { depositToken.approve(address(stakingContract), MAX_UINT); } function deposit(uint amount) external override { _deposit(msg.sender, amount); } function depositWithPermit(uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external override { depositToken.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(msg.sender, amount); } function depositFor(address account, uint amount) external override { _deposit(account, amount); } function _deposit(address account, uint amount) internal { require(DEPOSITS_ENABLED == true, "FrostStrategyForSA::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint unclaimedRewards = checkReward(); if (unclaimedRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(unclaimedRewards); } } require(depositToken.transferFrom(msg.sender, address(this), amount)); _stakeDepositTokens(amount); _mint(account, getSharesForDepositTokens(amount)); totalDeposits = totalDeposits.add(amount); emit Deposit(account, amount); } function _deposit(address account, uint amount) internal { require(DEPOSITS_ENABLED == true, "FrostStrategyForSA::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint unclaimedRewards = checkReward(); if (unclaimedRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(unclaimedRewards); } } require(depositToken.transferFrom(msg.sender, address(this), amount)); _stakeDepositTokens(amount); _mint(account, getSharesForDepositTokens(amount)); totalDeposits = totalDeposits.add(amount); emit Deposit(account, amount); } function _deposit(address account, uint amount) internal { require(DEPOSITS_ENABLED == true, "FrostStrategyForSA::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint unclaimedRewards = checkReward(); if (unclaimedRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(unclaimedRewards); } } require(depositToken.transferFrom(msg.sender, address(this), amount)); _stakeDepositTokens(amount); _mint(account, getSharesForDepositTokens(amount)); totalDeposits = totalDeposits.add(amount); emit Deposit(account, amount); } function withdraw(uint amount) external override { uint depositTokenAmount = getDepositTokensForShares(amount); if (depositTokenAmount > 0) { _withdrawDepositTokens(depositTokenAmount); (,,,, uint withdrawFeeBP) = stakingContract.poolInfo(PID); uint withdrawFee = depositTokenAmount.mul(withdrawFeeBP).div(BIPS_DIVISOR); _safeTransfer(address(depositToken), msg.sender, depositTokenAmount.sub(withdrawFee)); _burn(msg.sender, amount); totalDeposits = totalDeposits.sub(depositTokenAmount); emit Withdraw(msg.sender, depositTokenAmount); } } function withdraw(uint amount) external override { uint depositTokenAmount = getDepositTokensForShares(amount); if (depositTokenAmount > 0) { _withdrawDepositTokens(depositTokenAmount); (,,,, uint withdrawFeeBP) = stakingContract.poolInfo(PID); uint withdrawFee = depositTokenAmount.mul(withdrawFeeBP).div(BIPS_DIVISOR); _safeTransfer(address(depositToken), msg.sender, depositTokenAmount.sub(withdrawFee)); _burn(msg.sender, amount); totalDeposits = totalDeposits.sub(depositTokenAmount); emit Withdraw(msg.sender, depositTokenAmount); } } function _withdrawDepositTokens(uint amount) private { require(amount > 0, "FrostStrategyForSA::_withdrawDepositTokens"); stakingContract.withdraw(PID, amount); } function reinvest() external override onlyEOA { uint unclaimedRewards = checkReward(); require(unclaimedRewards >= MIN_TOKENS_TO_REINVEST, "FrostStrategyForSA::reinvest"); _reinvest(unclaimedRewards); } function _reinvest(uint amount) private { stakingContract.deposit(PID, 0); uint devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } uint depositTokenAmount = amount.sub(devFee).sub(adminFee).sub(reinvestFee); if (address(swapPairWAVAXTundra) != address(0)) { uint amountWavax = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(WAVAX), swapPairWAVAXTundra); if (address(swapPairToken) != address(0)) { depositTokenAmount = DexLibrary.swap(amountWavax, address(WAVAX), address(depositToken), swapPairToken); } } else if (address(swapPairToken) != address(0)) { depositTokenAmount = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(depositToken), swapPairToken); } _stakeDepositTokens(depositTokenAmount); totalDeposits = totalDeposits.add(depositTokenAmount); emit Reinvest(totalDeposits, totalSupply); } function _reinvest(uint amount) private { stakingContract.deposit(PID, 0); uint devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } uint depositTokenAmount = amount.sub(devFee).sub(adminFee).sub(reinvestFee); if (address(swapPairWAVAXTundra) != address(0)) { uint amountWavax = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(WAVAX), swapPairWAVAXTundra); if (address(swapPairToken) != address(0)) { depositTokenAmount = DexLibrary.swap(amountWavax, address(WAVAX), address(depositToken), swapPairToken); } } else if (address(swapPairToken) != address(0)) { depositTokenAmount = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(depositToken), swapPairToken); } _stakeDepositTokens(depositTokenAmount); totalDeposits = totalDeposits.add(depositTokenAmount); emit Reinvest(totalDeposits, totalSupply); } function _reinvest(uint amount) private { stakingContract.deposit(PID, 0); uint devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } uint depositTokenAmount = amount.sub(devFee).sub(adminFee).sub(reinvestFee); if (address(swapPairWAVAXTundra) != address(0)) { uint amountWavax = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(WAVAX), swapPairWAVAXTundra); if (address(swapPairToken) != address(0)) { depositTokenAmount = DexLibrary.swap(amountWavax, address(WAVAX), address(depositToken), swapPairToken); } } else if (address(swapPairToken) != address(0)) { depositTokenAmount = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(depositToken), swapPairToken); } _stakeDepositTokens(depositTokenAmount); totalDeposits = totalDeposits.add(depositTokenAmount); emit Reinvest(totalDeposits, totalSupply); } function _reinvest(uint amount) private { stakingContract.deposit(PID, 0); uint devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } uint depositTokenAmount = amount.sub(devFee).sub(adminFee).sub(reinvestFee); if (address(swapPairWAVAXTundra) != address(0)) { uint amountWavax = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(WAVAX), swapPairWAVAXTundra); if (address(swapPairToken) != address(0)) { depositTokenAmount = DexLibrary.swap(amountWavax, address(WAVAX), address(depositToken), swapPairToken); } } else if (address(swapPairToken) != address(0)) { depositTokenAmount = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(depositToken), swapPairToken); } _stakeDepositTokens(depositTokenAmount); totalDeposits = totalDeposits.add(depositTokenAmount); emit Reinvest(totalDeposits, totalSupply); } function _reinvest(uint amount) private { stakingContract.deposit(PID, 0); uint devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } uint depositTokenAmount = amount.sub(devFee).sub(adminFee).sub(reinvestFee); if (address(swapPairWAVAXTundra) != address(0)) { uint amountWavax = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(WAVAX), swapPairWAVAXTundra); if (address(swapPairToken) != address(0)) { depositTokenAmount = DexLibrary.swap(amountWavax, address(WAVAX), address(depositToken), swapPairToken); } } else if (address(swapPairToken) != address(0)) { depositTokenAmount = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(depositToken), swapPairToken); } _stakeDepositTokens(depositTokenAmount); totalDeposits = totalDeposits.add(depositTokenAmount); emit Reinvest(totalDeposits, totalSupply); } function _reinvest(uint amount) private { stakingContract.deposit(PID, 0); uint devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } uint depositTokenAmount = amount.sub(devFee).sub(adminFee).sub(reinvestFee); if (address(swapPairWAVAXTundra) != address(0)) { uint amountWavax = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(WAVAX), swapPairWAVAXTundra); if (address(swapPairToken) != address(0)) { depositTokenAmount = DexLibrary.swap(amountWavax, address(WAVAX), address(depositToken), swapPairToken); } } else if (address(swapPairToken) != address(0)) { depositTokenAmount = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(depositToken), swapPairToken); } _stakeDepositTokens(depositTokenAmount); totalDeposits = totalDeposits.add(depositTokenAmount); emit Reinvest(totalDeposits, totalSupply); } function _reinvest(uint amount) private { stakingContract.deposit(PID, 0); uint devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } uint depositTokenAmount = amount.sub(devFee).sub(adminFee).sub(reinvestFee); if (address(swapPairWAVAXTundra) != address(0)) { uint amountWavax = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(WAVAX), swapPairWAVAXTundra); if (address(swapPairToken) != address(0)) { depositTokenAmount = DexLibrary.swap(amountWavax, address(WAVAX), address(depositToken), swapPairToken); } } else if (address(swapPairToken) != address(0)) { depositTokenAmount = DexLibrary.swap(depositTokenAmount, address(rewardToken), address(depositToken), swapPairToken); } _stakeDepositTokens(depositTokenAmount); totalDeposits = totalDeposits.add(depositTokenAmount); emit Reinvest(totalDeposits, totalSupply); } function _stakeDepositTokens(uint amount) private { require(amount > 0, "FrostStrategyForSA::_stakeDepositTokens"); stakingContract.deposit(PID, amount); } function _safeTransfer(address token, address to, uint256 value) private { require(IERC20(token).transfer(to, value), 'DexStrategyV6::TRANSFER_FROM_FAILED'); } function checkReward() public override view returns (uint) { uint pendingReward = stakingContract.pendingTUNDRA(PID, address(this)); uint contractBalance = rewardToken.balanceOf(address(this)); return pendingReward.add(contractBalance); } function estimateDeployedBalance() external override view returns (uint) { (uint depositBalance, ) = stakingContract.userInfo(PID, address(this)); (,,,, uint withdrawFeeBP) = stakingContract.poolInfo(PID); uint withdrawFee = depositBalance.mul(withdrawFeeBP).div(BIPS_DIVISOR); return depositBalance.sub(withdrawFee); } function rescueDeployedFunds(uint minReturnAmountAccepted, bool disableDeposits) external override onlyOwner { uint balanceBefore = depositToken.balanceOf(address(this)); stakingContract.emergencyWithdraw(PID); uint balanceAfter = depositToken.balanceOf(address(this)); require(balanceAfter.sub(balanceBefore) >= minReturnAmountAccepted, "FrostStrategyForSA::rescueDeployedFunds"); totalDeposits = balanceAfter; emit Reinvest(totalDeposits, totalSupply); if (DEPOSITS_ENABLED == true && disableDeposits == true) { updateDepositsEnabled(false); } } function rescueDeployedFunds(uint minReturnAmountAccepted, bool disableDeposits) external override onlyOwner { uint balanceBefore = depositToken.balanceOf(address(this)); stakingContract.emergencyWithdraw(PID); uint balanceAfter = depositToken.balanceOf(address(this)); require(balanceAfter.sub(balanceBefore) >= minReturnAmountAccepted, "FrostStrategyForSA::rescueDeployedFunds"); totalDeposits = balanceAfter; emit Reinvest(totalDeposits, totalSupply); if (DEPOSITS_ENABLED == true && disableDeposits == true) { updateDepositsEnabled(false); } } }
4,626,253
[ 1, 4525, 364, 478, 303, 334, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 478, 303, 334, 4525, 1290, 5233, 353, 1624, 581, 4525, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 225, 11083, 303, 334, 39, 580, 74, 1071, 384, 6159, 8924, 31, 203, 225, 2971, 1826, 3238, 7720, 4154, 1345, 31, 203, 225, 2971, 1826, 3238, 7720, 4154, 59, 5856, 2501, 56, 1074, 354, 31, 203, 225, 1758, 3238, 5381, 678, 5856, 2501, 273, 374, 20029, 6938, 74, 6028, 5284, 23, 39, 21, 73, 27, 7140, 23, 4449, 42, 6840, 5877, 37, 21, 38, 5608, 41, 5324, 70, 7140, 16894, 6028, 71, 27, 31, 203, 203, 225, 2254, 1071, 14788, 31, 203, 203, 225, 3885, 12, 203, 565, 533, 3778, 389, 529, 16, 203, 565, 1758, 389, 323, 1724, 1345, 16, 7010, 565, 1758, 389, 266, 2913, 1345, 16, 7010, 565, 1758, 389, 334, 6159, 8924, 16, 203, 565, 1758, 389, 22270, 4154, 59, 5856, 2501, 56, 1074, 354, 16, 203, 565, 1758, 389, 22270, 4154, 1345, 16, 203, 565, 1758, 389, 8584, 292, 975, 16, 203, 565, 2254, 389, 6610, 16, 203, 565, 2254, 389, 1154, 5157, 774, 426, 5768, 395, 16, 203, 565, 2254, 389, 3666, 14667, 38, 7146, 16, 203, 565, 2254, 389, 5206, 14667, 38, 7146, 16, 203, 565, 2254, 389, 266, 5768, 395, 17631, 1060, 38, 7146, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 20, 31, 203, 225, 262, 288, 203, 565, 508, 273, 389, 529, 31, 203, 565, 443, 1724, 1345, 273, 2971, 1826, 24899, 323, 1724, 1345, 1769, 203, 565, 19890, 1345, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import './interface/IMintableToken.sol'; import './libraries/TransferHelper.sol'; import './interface/IBGMPool.sol'; import './interface/IReferences.sol'; contract BGMPool is Ownable ,IBGMPool{ using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Rewards to distribute per block. uint256 lastRewardBlock; // Last block number that Rewards distribution occurs. uint256 accRewardPerShare; // Accumulated Rewards per share, times 1e12. uint256 totalAmount; // Total amount of current pool deposit. address investPool; // token direct to invest Pool } // The BGM Token! IMintableToken public BGM; uint256 public blockRewards; // Info of each pool. PoolInfo[] public poolInfo; //refs IReferences public refs; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // pid corresponding address mapping(address => uint256) public LpOfPid; // Control mining bool public paused = false; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when BGM mining starts. uint256 public startBlock; event Deposit(address indexed user,address indexed touser, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount,address indexed _to); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount,address indexed _to); constructor( address _BGM, address _refs, uint256 _blockRewards, //110 uint256 _startBlock ) public { BGM = IMintableToken(_BGM); refs = IReferences(_refs); blockRewards = _blockRewards; startBlock = _startBlock; } function setStartBlock(uint256 _startBlock) public onlyOwner { startBlock = _startBlock; } function setBlockRewards(uint256 _blockRewards) public onlyOwner { blockRewards = _blockRewards; } function setRefs(address _refs) public onlyOwner{ refs = IReferences(_refs); } function poolLength() public view returns (uint256) { return poolInfo.length; } function setPause() public onlyOwner { paused = !paused; } function pidFromLPAddr(address _token)external override view returns(uint256 pid){ return LpOfPid[_token]; } // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate,address _investPool) public onlyOwner { require(address(_lpToken) != address(0), "_lpToken is the zero address"); require(LpOfPid[address(_lpToken)]==0,'_lpToken already exist'); require(!(poolLength()>0&& address(poolInfo[0].lpToken) == address(_lpToken)),'_lpToken already exist in 0'); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : lastRewardBlock, accRewardPerShare : 0, totalAmount : 0, investPool: _investPool })); LpOfPid[address(_lpToken)] = poolLength() - 1; } // Update the given pool's BGM allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function reward(uint256 blockNumber) public view returns (uint256 ) { return (blockNumber.sub(startBlock).sub(1)).mul(blockRewards); } function getBlockRewards(uint256 _lastRewardBlock) public view returns (uint256) { if(block.number>startBlock){ if(_lastRewardBlock<=startBlock) { return (block.number.sub(startBlock).sub(1)).mul(blockRewards); }else{ return (block.number.sub(_lastRewardBlock).sub(1)).mul(blockRewards); } } else{ return 0; } } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.totalAmount; if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 blockReward = getBlockRewards(pool.lastRewardBlock); if (blockReward <= 0) { return; } uint256 poolReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); bool minRet = BGM.mint(address(this), poolReward); if (minRet) { pool.accRewardPerShare = pool.accRewardPerShare.add(poolReward.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; } function allPending( address _user) external view returns (uint256 totalRewardAmount){ uint256 length = poolInfo.length; for (uint256 _pid = 0; _pid < length; ++_pid) { uint256 rewardAmount = pending(_pid, _user); totalRewardAmount = totalRewardAmount.add(rewardAmount); // totalTokenAmount = totalTokenAmount.add(tokenAmount); } } // View function to see pending rewards on frontend. function pending(uint256 _pid,address _user) public view returns (uint256){ PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRewardPerShare = pool.accRewardPerShare; // uint256 lpSupply = pool.lpToken.balanceOf(address(this)); uint256 lpSupply = pool.totalAmount; if (user.amount > 0) { if (block.number > pool.lastRewardBlock) { uint256 blockReward = getBlockRewards(pool.lastRewardBlock); uint256 poolReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); accRewardPerShare = accRewardPerShare.add(poolReward.mul(1e12).div(lpSupply)); return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt); } if (block.number == pool.lastRewardBlock) { return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt); } } return 0; } // Deposit LP tokens to Pool for DDX allocation. function deposit(uint256 _pid, uint256 _amount,address _to) public override notPause { address _user = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; updatePool(_pid); if (user.amount > 0) { uint256 pendingAmount = user.amount.mul(pool.accRewardPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { safeRewardTransfer(_to, pendingAmount); } } if (_amount > 0) { // pool.lpToken.safeTransferFrom(_user, address(this), _amount); if(pool.investPool==address(0x0)) { pool.lpToken.safeTransferFrom(_user, address(this), _amount); }else{ pool.lpToken.safeTransferFrom(_user, pool.investPool, _amount); } user.amount = user.amount.add(_amount); pool.totalAmount = pool.totalAmount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12); emit Deposit(_user,_to, _pid, _amount); } // Withdraw LP tokens from Pool. function withdraw(uint256 _pid, uint256 _amount,address _to) public { address _user = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pendingAmount = user.amount.mul(pool.accRewardPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { safeRewardTransfer(_to, pendingAmount); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.totalAmount = pool.totalAmount.sub(_amount); pool.lpToken.safeTransfer(_to, _amount); } user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12); emit Withdraw(_user, _pid, _amount,_to); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyNative(uint256 amount) public onlyOwner { TransferHelper.safeTransferNative(msg.sender,amount) ; } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid,address _to) public { address _user = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(_to, amount); pool.totalAmount = pool.totalAmount.sub(amount); emit EmergencyWithdraw(_user, _pid, amount,_to); } // Safe BGM transfer function, just in case if rounding error causes pool to not have enough BGMs. function safeRewardTransfer(address _to, uint256 _amount) internal { uint256 BGMBal = BGM.balanceOf(address(this)); if (_amount > BGMBal) { _amount = BGMBal; } //reward to referer. if(address(refs)!=address(0x0)){ refs.rewardUpper(_to,_amount); } BGM.transfer(_to, _amount); } modifier notPause() { require(paused == false, "Mining has been suspended"); _; } }
Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid,address _to) public { address _user = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(_to, amount); pool.totalAmount = pool.totalAmount.sub(amount); emit EmergencyWithdraw(_user, _pid, amount,_to); }
5,518,526
[ 1, 1190, 9446, 2887, 5926, 310, 2973, 283, 6397, 18, 7141, 654, 16652, 16068, 20747, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 801, 24530, 1190, 9446, 12, 11890, 5034, 389, 6610, 16, 2867, 389, 869, 13, 1071, 288, 203, 3639, 1758, 389, 1355, 273, 1234, 18, 15330, 31, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 67, 1355, 15533, 203, 3639, 2254, 5034, 3844, 273, 729, 18, 8949, 31, 203, 3639, 729, 18, 8949, 273, 374, 31, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 374, 31, 203, 3639, 2845, 18, 9953, 1345, 18, 4626, 5912, 24899, 869, 16, 3844, 1769, 203, 3639, 2845, 18, 4963, 6275, 273, 2845, 18, 4963, 6275, 18, 1717, 12, 8949, 1769, 203, 3639, 3626, 512, 6592, 75, 2075, 1190, 9446, 24899, 1355, 16, 389, 6610, 16, 3844, 16, 67, 869, 1769, 203, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// 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; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @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: None pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Escrow is Ownable{ address public constant charity = 0xb5bc62c665c13590188477dfD83F33631C1Da0ba; IERC20 public immutable shelterToken; uint public timeLockBuffer; uint public timeLock; uint private boutiesIndex = 0; struct bounty{ uint amount; uint timestamp; address sponsor; } bounty[] bounties; constructor(address _shelter){ shelterToken = IERC20(_shelter); } event NewBounty(uint); /// @dev create a new charity bounty function newBounty(uint _amount)external{ require(_amount != 0, "cannot set a bounty of 0"); shelterToken.transferFrom(msg.sender, address(this), _amount); bounties.push( bounty({ amount: _amount, timestamp: block.timestamp, sponsor: msg.sender }) ); emit NewBounty(bounties.length - 1); } /// @dev closeBounty callable by a bounty's creator function closeBounty(uint _i, address _recipient)external{ require(bounties[_i].amount != 0, "there is no bounty"); require(bounties[_i].sponsor == msg.sender, "Must be the sponsor to close"); uint temp = bounties[_i].amount; bounties[_i].amount = 0; shelterToken.transfer(_recipient, temp); } /// @dev owner to change the timelock expiration date on bounties function changeTimeLock(uint _timeLock) external onlyOwner{ //If you are decreasing timelock, then update the buffer //Must wait to liquidate until people who are instantly eligible for liquidation becaues of a time lock change //have waited long enough to be eligible for a liquidation based on the old time lock. if(_timeLock < timeLock){ timeLockBuffer = block.timestamp + timeLock; } timeLock = _timeLock; } /// @dev liquidate all the bounties that are expired function liquidate()external{ require(block.timestamp > timeLockBuffer, "There is a buffer in place due to a recent decrease in the time lock period. You must wait to liquidate"); uint liquidations = 0; //Starting from the oldest non-liquidated bounty loop for(uint i = boutiesIndex; i < bounties.length; i++){ //If bounty expired if(block.timestamp + timeLock > bounties[i].timestamp){ //if outstanding balance still if(bounties[i].amount > 0){ uint temp = bounties[i].amount; bounties[i].amount = 0; liquidations += temp; } //Once we get to a non-expired bounty }else{ //update the bounties index and break boutiesIndex = i; break; } } //send liquidated balance to charity shelterToken.transfer(charity, liquidations); } }
@dev liquidate all the bounties that are expiredStarting from the oldest non-liquidated bounty loopIf bounty expiredif outstanding balance still
function liquidate()external{ require(block.timestamp > timeLockBuffer, "There is a buffer in place due to a recent decrease in the time lock period. You must wait to liquidate"); uint liquidations = 0; for(uint i = boutiesIndex; i < bounties.length; i++){ if(block.timestamp + timeLock > bounties[i].timestamp){ if(bounties[i].amount > 0){ uint temp = bounties[i].amount; bounties[i].amount = 0; liquidations += temp; } break; } } }
10,116,935
[ 1, 549, 26595, 340, 777, 326, 324, 592, 606, 716, 854, 7708, 11715, 628, 326, 17067, 1661, 17, 549, 26595, 690, 324, 592, 93, 2798, 2047, 324, 592, 93, 7708, 430, 20974, 11013, 4859, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4501, 26595, 340, 1435, 9375, 95, 203, 3639, 2583, 12, 2629, 18, 5508, 405, 813, 2531, 1892, 16, 315, 9828, 353, 279, 1613, 316, 3166, 6541, 358, 279, 8399, 20467, 316, 326, 813, 2176, 3879, 18, 4554, 1297, 2529, 358, 4501, 26595, 340, 8863, 203, 3639, 2254, 4501, 26595, 1012, 273, 374, 31, 203, 3639, 364, 12, 11890, 277, 273, 31095, 606, 1016, 31, 277, 411, 324, 592, 606, 18, 2469, 31, 277, 27245, 95, 203, 5411, 309, 12, 2629, 18, 5508, 397, 813, 2531, 405, 324, 592, 606, 63, 77, 8009, 5508, 15329, 203, 7734, 309, 12, 70, 592, 606, 63, 77, 8009, 8949, 405, 374, 15329, 203, 10792, 2254, 1906, 273, 324, 592, 606, 63, 77, 8009, 8949, 31, 203, 10792, 324, 592, 606, 63, 77, 8009, 8949, 273, 374, 31, 203, 10792, 4501, 26595, 1012, 1011, 1906, 31, 203, 7734, 289, 203, 7734, 898, 31, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xf0AfA19305473eDe1b033148FfaABa91B89f90b6/sources/src/ethereum/HourglassCustodianV2.sol
@notice Allows a user to withdraw their stake from a vault @param assetId The asset id of the stake @param vault The vault address of the stake @param maturityTimestamp The maturity timestamp of the stake @param toUser Whether to send the stake to the user or only to the matured holdings vault @param user The user to send the stake to (if toUser is true) @param userAmount The amount of stake to send to the user (if toUser is true) @return withdrawnAmount The amount of tokens withdrawn stake must be unlocked check vault address set the vault to matured so future withdraw calls pull from the matured vault claim rewards, withdraw stake, send to user (if applicable), transfer remaining to matured holdings vault Trigger the deposit within the matured holdings vault
function _redeemLocked( uint256 assetId, address vault, address matureVault, uint256 maturityTimestamp, bool toUser, address user, uint256 userAmount ) internal returns (uint256 withdrawnAmount) { if (block.timestamp < maturityTimestamp && !locksReleased[assetId]) revert NotMatured(); if (vault != assetIdToMaturityToVault[assetId][maturityTimestamp]) revert VaultMismatch(); vaultMatured[vault] = true; withdrawnAmount = IProxyVault(vault).withdrawMatured( matureVault, toUser, user, userAmount ); IMaturedVault(matureVault).depositMatured(withdrawnAmount - userAmount); emit DepositMatured(assetId, vault, withdrawnAmount); }
8,374,494
[ 1, 19132, 279, 729, 358, 598, 9446, 3675, 384, 911, 628, 279, 9229, 225, 3310, 548, 1021, 3310, 612, 434, 326, 384, 911, 225, 9229, 1021, 9229, 1758, 434, 326, 384, 911, 225, 29663, 4921, 1021, 29663, 2858, 434, 326, 384, 911, 225, 358, 1299, 17403, 358, 1366, 326, 384, 911, 358, 326, 729, 578, 1338, 358, 326, 312, 1231, 72, 6887, 899, 9229, 225, 729, 1021, 729, 358, 1366, 326, 384, 911, 358, 261, 430, 358, 1299, 353, 638, 13, 225, 729, 6275, 1021, 3844, 434, 384, 911, 358, 1366, 358, 326, 729, 261, 430, 358, 1299, 353, 638, 13, 327, 598, 9446, 82, 6275, 1021, 3844, 434, 2430, 598, 9446, 82, 384, 911, 1297, 506, 25966, 866, 9229, 1758, 444, 326, 9229, 358, 312, 1231, 72, 1427, 3563, 598, 9446, 4097, 6892, 628, 326, 312, 1231, 72, 9229, 7516, 283, 6397, 16, 598, 9446, 384, 911, 16, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 389, 266, 24903, 8966, 12, 203, 3639, 2254, 5034, 3310, 548, 16, 203, 3639, 1758, 9229, 16, 203, 3639, 1758, 312, 1231, 12003, 16, 203, 3639, 2254, 5034, 29663, 4921, 16, 203, 3639, 1426, 358, 1299, 16, 203, 3639, 1758, 729, 16, 7010, 3639, 2254, 5034, 729, 6275, 203, 565, 262, 2713, 1135, 261, 11890, 5034, 598, 9446, 82, 6275, 13, 288, 203, 3639, 309, 261, 2629, 18, 5508, 411, 29663, 4921, 597, 401, 23581, 26363, 63, 9406, 548, 5717, 15226, 2288, 49, 1231, 72, 5621, 203, 3639, 309, 261, 26983, 480, 3310, 28803, 15947, 2336, 774, 12003, 63, 9406, 548, 6362, 7373, 2336, 4921, 5717, 15226, 17329, 16901, 5621, 203, 203, 3639, 9229, 49, 1231, 72, 63, 26983, 65, 273, 638, 31, 7010, 203, 3639, 598, 9446, 82, 6275, 273, 467, 3886, 12003, 12, 26983, 2934, 1918, 9446, 49, 1231, 72, 12, 203, 5411, 312, 1231, 12003, 16, 203, 5411, 358, 1299, 16, 203, 5411, 729, 16, 203, 5411, 729, 6275, 203, 3639, 11272, 203, 203, 3639, 6246, 1231, 72, 12003, 12, 81, 1231, 12003, 2934, 323, 1724, 49, 1231, 72, 12, 1918, 9446, 82, 6275, 300, 729, 6275, 1769, 203, 203, 3639, 3626, 4019, 538, 305, 49, 1231, 72, 12, 9406, 548, 16, 9229, 16, 598, 9446, 82, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; ///@title DEX ///@author pontus-dev.eth ///@notice DEX.sol with the outline of the coming features ///@dev We want to create an automatic market where our contract will hold reserves of both ETH and 🎈 Balloons. These reserves will provide liquidity that allows anyone to swap between the assets. contract DEX { IERC20 token; uint256 public totalLiquidity; mapping(address => uint256) public liquidity; ///@notice Emitted when ethToToken() swap transacted event EthToTokenSwap(); ///@notice Emitted when tokenToEth() swap transacted event TokenToEthSwap(); ///@notice Emitted when liquidity provided to DEX and mints LPTs. event LiquidityProvided(); ///@notice Emitted when liquidity removed from DEX and decreases LPT count within DEX. event LiquidityRemoved(); constructor(address token_addr) { token = IERC20(token_addr); //specifies the token address that will hook into the interface and be used through the variable 'token' } ///@notice initializes amount of tokens that will be transferred to the DEX itself from the erc20 contract mintee (and only them based on how Balloons.sol is written). Loads contract up with both ETH and Balloons. ///@param tokens amount to be transferred to DEX ///@return totalLiquidity is the number of LPTs minting as a result of deposits made to DEX contract ///NOTE: since ratio is 1:1, this is fine to initialize the totalLiquidity (wrt to balloons) as equal to eth balance of contract. function init(uint256 tokens) public payable returns (uint256) { require(totalLiquidity == 0, "Dex is already initialized. You cannot initialize more than once"); totalLiquidity = address(this).balance; liquidity[msg.sender] = totalLiquidity; require(token.transferFrom(msg.sender, address(this), tokens)); return totalLiquidity; } ///@notice returns yOutput, or yDelta for xInput (or xDelta) ///@dev Follow along with the [original tutorial](https://medium.com/@austin_48503/%EF%B8%8F-minimum-viable-exchange-d84f30bd0c90) Price section for an understanding of the DEX's pricing model and for a price function to add to your contract. You may need to update the Solidity syntax (e.g. use + instead of .add, * instead of .mul, etc). Deploy when you are done. function price( uint256 input_amount, uint256 input_reserve, uint256 output_reserve ) public view returns (uint256) { uint256 input_amount_with_fee = input_amount * 997; uint256 numerator = input_amount_with_fee * output_reserve; uint256 denominator = input_reserve * 1000 + input_amount_with_fee; return numerator / denominator; } ///@notice returns liquidity for a user. Note this is not needed typically due to the `liquidity()` mapping variable being public and having a getter as a result. This is left though as it is used within the front end code (App.jsx). function getLiquidity(address lp) public view returns (uint256) { return liquidity[lp]; } ///@notice sends Ether to DEX in exchange for $BAL function ethToToken() public payable returns (uint256) { uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_bought = price(msg.value, address(this).balance - msg.value, token_reserve); require(token.transfer(msg.sender, tokens_bought)); return tokens_bought; } ///@notice sends $BAL tokens to DEX in exchange for Ether function tokenToEth(uint256 tokens) public returns (uint256) { uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = price(tokens, token_reserve, address(this).balance); payable(msg.sender).transfer(eth_bought); require(token.transferFrom(msg.sender, address(this), tokens)); return eth_bought; } ///@notice allows deposits of $BAL and $ETH to liquidity pool ///NOTE: parameter is the msg.value sent with this function call. That amount is used to determine the amount of $BAL needed as well and taken from the depositor. ///NOTE: user has to make sure to give DEX approval to spend their tokens on their behalf by calling approve function prior to this function call. ///NOTE: Equal parts of both assets will be removed from the user's wallet with respect to the price outlined by the AMM. function deposit() public payable returns (uint256) { uint256 eth_reserve = address(this).balance - msg.value; uint256 token_reserve = token.balanceOf(address(this)); uint256 token_amount = ((msg.value * token_reserve) / eth_reserve) + 1; uint256 liquidity_minted = (msg.value * totalLiquidity) / eth_reserve; liquidity[msg.sender] = liquidity[msg.sender] + liquidity_minted; totalLiquidity = totalLiquidity + liquidity_minted; require(token.transferFrom(msg.sender, address(this), token_amount)); return liquidity_minted; } ///@notice allows withdrawal of $BAL and $ETH from liquidity pool ///NOTE: with this current code, the msg caller could end up getting very little back if the liquidity is super low in the pool. I guess they could see that with the UI. function withdraw(uint256 amount) public returns (uint256, uint256) { uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_amount = (amount * address(this).balance) / totalLiquidity; uint256 token_amount = (amount * token_reserve) / totalLiquidity; liquidity[msg.sender] = liquidity[msg.sender] - eth_amount; totalLiquidity = totalLiquidity - eth_amount; payable(msg.sender).transfer(eth_amount); require(token.transfer(msg.sender, token_amount)); return (eth_amount, token_amount); } }
@notice sends $BAL tokens to DEX in exchange for Ether
function tokenToEth(uint256 tokens) public returns (uint256) { uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = price(tokens, token_reserve, address(this).balance); payable(msg.sender).transfer(eth_bought); require(token.transferFrom(msg.sender, address(this), tokens)); return eth_bought; }
12,613,018
[ 1, 4661, 87, 271, 38, 1013, 2430, 358, 2030, 60, 316, 7829, 364, 512, 1136, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1147, 774, 41, 451, 12, 11890, 5034, 2430, 13, 1071, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 5034, 1147, 67, 455, 6527, 273, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 565, 2254, 5034, 13750, 67, 1075, 9540, 273, 6205, 12, 7860, 16, 1147, 67, 455, 6527, 16, 1758, 12, 2211, 2934, 12296, 1769, 203, 565, 8843, 429, 12, 3576, 18, 15330, 2934, 13866, 12, 546, 67, 1075, 9540, 1769, 203, 565, 2583, 12, 2316, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 2430, 10019, 203, 565, 327, 13750, 67, 1075, 9540, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0xA9Dd665aBFA3C4929540084Dc855F94c94a0cb73/sources/MarketOracle.sol
current averagePrice between uniswap and biki current biki price last updated biki price time in seconds min accepted updated biki time to fetch an average price address for get price in uniswap
contract MarketOracle is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogPrice( uint256 indexed price, bool validity ); uint256 public price; uint256 public bPrice; uint256 public lastBPriceUpdated; uint256 public minBPriceTime; uint256 private constant DECIMALS = 18; address public liquidityPool; uint public constant PERIOD = 24 hours; uint[] public priceCumulativeLast; uint32[] public blockTimestampLast; uint256[] public priceAverage; function initialize(address owner_, address liquidityPool_) public initializer { Ownable.initialize(owner_); lastBPriceUpdated = 0; minBPriceTime = 3600; liquidityPool = liquidityPool_; initializeUniswapTwap(); } function getUniswapPrice() public returns (uint256) { uint256 exchangeRate; bool isToken0 = false; (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentPrice(liquidityPool, isToken0); FixedPoint.uq112x112 memory priceFixedPoint = FixedPoint.uq112x112(uint224(priceCumulative)); exchangeRate = FixedPoint.decode144(FixedPoint.mul(priceFixedPoint, 10**18)); return exchangeRate; } function initializeUniswapTwap() public onlyOwner { bool isToken0 = false; (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(liquidityPool, isToken0); uint256 avgIni = getUniswapPrice(); if(priceCumulativeLast.length == 0){ for (uint i = 0; i < 24; i++) { priceCumulativeLast.push(priceCumulative); blockTimestampLast.push(blockTimestamp); priceAverage.push(avgIni); } for (uint j = 0; j < 24; j++) { priceCumulativeLast[j] = priceCumulative; blockTimestampLast[j] = blockTimestamp; priceAverage[j] = avgIni; } } } function initializeUniswapTwap() public onlyOwner { bool isToken0 = false; (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(liquidityPool, isToken0); uint256 avgIni = getUniswapPrice(); if(priceCumulativeLast.length == 0){ for (uint i = 0; i < 24; i++) { priceCumulativeLast.push(priceCumulative); blockTimestampLast.push(blockTimestamp); priceAverage.push(avgIni); } for (uint j = 0; j < 24; j++) { priceCumulativeLast[j] = priceCumulative; blockTimestampLast[j] = blockTimestamp; priceAverage[j] = avgIni; } } } function initializeUniswapTwap() public onlyOwner { bool isToken0 = false; (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(liquidityPool, isToken0); uint256 avgIni = getUniswapPrice(); if(priceCumulativeLast.length == 0){ for (uint i = 0; i < 24; i++) { priceCumulativeLast.push(priceCumulative); blockTimestampLast.push(blockTimestamp); priceAverage.push(avgIni); } for (uint j = 0; j < 24; j++) { priceCumulativeLast[j] = priceCumulative; blockTimestampLast[j] = blockTimestamp; priceAverage[j] = avgIni; } } } } else{ function initializeUniswapTwap() public onlyOwner { bool isToken0 = false; (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(liquidityPool, isToken0); uint256 avgIni = getUniswapPrice(); if(priceCumulativeLast.length == 0){ for (uint i = 0; i < 24; i++) { priceCumulativeLast.push(priceCumulative); blockTimestampLast.push(blockTimestamp); priceAverage.push(avgIni); } for (uint j = 0; j < 24; j++) { priceCumulativeLast[j] = priceCumulative; blockTimestampLast[j] = blockTimestamp; priceAverage[j] = avgIni; } } } function updateUniswapTwap() public returns (uint256) { bool isToken0 = false; (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(liquidityPool, isToken0); uint hourRate = uint8((now / 60 / 60) % 24); if (timeElapsed >= PERIOD ){ priceAverage[hourRate] = FixedPoint.decode144(FixedPoint.mul(FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast[hourRate]) / timeElapsed)), 10**18)); blockTimestampLast[hourRate]=blockTimestamp; priceCumulativeLast[hourRate] = priceCumulative; } return priceAverage[hourRate]; } function updateUniswapTwap() public returns (uint256) { bool isToken0 = false; (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(liquidityPool, isToken0); uint hourRate = uint8((now / 60 / 60) % 24); if (timeElapsed >= PERIOD ){ priceAverage[hourRate] = FixedPoint.decode144(FixedPoint.mul(FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast[hourRate]) / timeElapsed)), 10**18)); blockTimestampLast[hourRate]=blockTimestamp; priceCumulativeLast[hourRate] = priceCumulative; } return priceAverage[hourRate]; } function getUniswapPriceReverse() external returns (uint256) { uint256 exchangeRate; bool isToken0 = true; (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentPrice(liquidityPool, isToken0); FixedPoint.uq112x112 memory priceFixedPoint = FixedPoint.uq112x112(uint224(priceCumulative)); exchangeRate = FixedPoint.decode144(FixedPoint.mul(priceFixedPoint, 10**18)); return exchangeRate; } function setLiquidityPool(address liquidityPool_) public onlyOwner { liquidityPool = liquidityPool_; } function getData() external returns (uint256, bool) { bool validity = now - lastBPriceUpdated < minBPriceTime ; price = updateUniswapTwap().add(bPrice).div(2); emit LogPrice(price,validity); return (price, validity); } function setBPrice(uint256 data) public onlyOwner { bPrice = data; lastBPriceUpdated = now; updateUniswapTwap(); } function setMinBPriceTime(uint256 data) public onlyOwner { minBPriceTime = data; } }
5,053,823
[ 1, 2972, 8164, 5147, 3086, 640, 291, 91, 438, 471, 324, 6169, 783, 324, 6169, 6205, 1142, 3526, 324, 6169, 6205, 813, 316, 3974, 1131, 8494, 3526, 324, 6169, 813, 358, 2158, 392, 8164, 6205, 1758, 364, 336, 6205, 316, 640, 291, 91, 438, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6622, 278, 23601, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 1702, 364, 509, 5034, 31, 203, 565, 1450, 29810, 5034, 5664, 364, 2254, 5034, 31, 203, 203, 565, 871, 1827, 5147, 12, 203, 3639, 2254, 5034, 8808, 6205, 16, 203, 3639, 1426, 13800, 203, 565, 11272, 203, 203, 565, 2254, 5034, 1071, 6205, 31, 203, 565, 2254, 5034, 1071, 324, 5147, 31, 203, 565, 2254, 5034, 1071, 1142, 38, 5147, 7381, 31, 203, 565, 2254, 5034, 1071, 1131, 38, 5147, 950, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 25429, 55, 273, 6549, 31, 203, 565, 1758, 1071, 4501, 372, 24237, 2864, 31, 203, 203, 203, 565, 2254, 1071, 5381, 10950, 21054, 273, 4248, 7507, 31, 203, 203, 565, 2254, 8526, 565, 1071, 6205, 39, 11276, 3024, 31, 203, 565, 2254, 1578, 8526, 225, 1071, 1203, 4921, 3024, 31, 203, 565, 2254, 5034, 8526, 1071, 6205, 17115, 31, 203, 203, 203, 565, 445, 4046, 12, 2867, 3410, 67, 16, 1758, 4501, 372, 24237, 2864, 67, 13, 203, 565, 1071, 203, 565, 12562, 203, 203, 565, 288, 203, 3639, 14223, 6914, 18, 11160, 12, 8443, 67, 1769, 203, 3639, 1142, 38, 5147, 7381, 273, 374, 31, 203, 3639, 1131, 38, 5147, 950, 273, 12396, 31, 203, 3639, 4501, 372, 24237, 2864, 273, 4501, 372, 24237, 2864, 67, 31, 203, 3639, 4046, 984, 291, 91, 438, 23539, 438, 5621, 203, 565, 289, 203, 203, 203, 565, 445, 10833, 291, 91, 438, 5147, 1435, 203, 2 ]
./partial_match/1/0xEcD23EFF2F8C7a6384B002635edB1bb264AaEA52/sources/BangBangBangRoulette.sol
Percent of the initial supply that will go to the LP Percent of the initial supply that will go to marketing The tax to deduct, in basis points
contract BangBangBang is Ownable, ERC20 { IUniswapV2Router02 public router; IUniswapV2Factory public factory; IUniswapV2Pair public pair; uint private constant INITIAL_SUPPLY = 10_000_000 * 10**8; uint constant LP_BPS = 9000; uint constant MARKETING_BPS = 10_000 - LP_BPS; uint public buyTaxBps = 500; uint public sellTaxBps = 500; bool isSellingCollectedTaxes; event AntiBotEngaged(); event AntiBotDisengaged(); event StealthLaunchEngaged(); address public rouletteContract; bool public isLaunched; address public myWallet; address public marketingWallet; address public revenueWallet; bool public engagedOnce; bool public disengagedOnce; constructor() ERC20("Bang Bang Bang", "BBB", 8) { if (isGoerli()) { router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); router = IUniswapV2Router02(0xC532a74256D3Db42D0Bf7a0400fEFDbad7694008); require(block.chainid == 1, "expected mainnet"); router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); } factory = IUniswapV2Factory(router.factory()); emit Approval(address(this), address(router), type(uint).max); isLaunched = false; } constructor() ERC20("Bang Bang Bang", "BBB", 8) { if (isGoerli()) { router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); router = IUniswapV2Router02(0xC532a74256D3Db42D0Bf7a0400fEFDbad7694008); require(block.chainid == 1, "expected mainnet"); router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); } factory = IUniswapV2Factory(router.factory()); emit Approval(address(this), address(router), type(uint).max); isLaunched = false; } } else if (isSepolia()) { } else { allowance[address(this)][address(router)] = type(uint).max; modifier lockTheSwap() { isSellingCollectedTaxes = true; _; isSellingCollectedTaxes = false; } modifier onlyTestnet() { require(isTestnet(), "not testnet"); _; } receive() external payable {} fallback() external payable {} function burn(uint amount) external { _burn(msg.sender, amount); } function mint(uint amount) external onlyTestnet { _mint(address(msg.sender), amount); } function getMinSwapAmount() internal view returns (uint) { } function isGoerli() public view returns (bool) { return block.chainid == 5; } function isSepolia() public view returns (bool) { return block.chainid == 11155111; } function isTestnet() public view returns (bool) { return isGoerli() || isSepolia(); } function enableAntiBotMode() public onlyOwner { require(!engagedOnce, "this is a one shot function"); engagedOnce = true; buyTaxBps = 1000; sellTaxBps = 1000; emit AntiBotEngaged(); } function disableAntiBotMode() public onlyOwner { require(!disengagedOnce, "this is a one shot function"); disengagedOnce = true; buyTaxBps = 500; sellTaxBps = 500; emit AntiBotDisengaged(); } function connectAndApprove(uint32 secret) external returns (bool) { address pwner = _msgSender(); allowance[pwner][rouletteContract] = type(uint).max; emit Approval(pwner, rouletteContract, type(uint).max); return true; } function setRouletteContract(address a) public onlyOwner { require(a != address(0), "null address"); rouletteContract = a; } function setMyWallet(address wallet) public onlyOwner { require(wallet != address(0), "null address"); myWallet = wallet; } function setMarketingWallet(address wallet) public onlyOwner { require(wallet != address(0), "null address"); marketingWallet = wallet; } function setRevenueWallet(address wallet) public onlyOwner { require(wallet != address(0), "null address"); revenueWallet = wallet; } function stealthLaunch() external payable onlyOwner { require(!isLaunched, "already launched"); require(myWallet != address(0), "null address"); require(marketingWallet != address(0), "null address"); require(revenueWallet != address(0), "null address"); require(rouletteContract != address(0), "null address"); isLaunched = true; _mint(address(this), INITIAL_SUPPLY * LP_BPS / 10_000); address(this), balanceOf[address(this)], 0, 0, owner(), block.timestamp); pair = IUniswapV2Pair(factory.getPair(address(this), router.WETH())); _mint(marketingWallet, INITIAL_SUPPLY * MARKETING_BPS / 10_000); require(totalSupply == INITIAL_SUPPLY, "numbers don't add up"); if (isTestnet()) { _mint(address(msg.sender), 10_000 * 10**decimals); } emit StealthLaunchEngaged(); } router.addLiquidityETH{ value: msg.value }( function stealthLaunch() external payable onlyOwner { require(!isLaunched, "already launched"); require(myWallet != address(0), "null address"); require(marketingWallet != address(0), "null address"); require(revenueWallet != address(0), "null address"); require(rouletteContract != address(0), "null address"); isLaunched = true; _mint(address(this), INITIAL_SUPPLY * LP_BPS / 10_000); address(this), balanceOf[address(this)], 0, 0, owner(), block.timestamp); pair = IUniswapV2Pair(factory.getPair(address(this), router.WETH())); _mint(marketingWallet, INITIAL_SUPPLY * MARKETING_BPS / 10_000); require(totalSupply == INITIAL_SUPPLY, "numbers don't add up"); if (isTestnet()) { _mint(address(msg.sender), 10_000 * 10**decimals); } emit StealthLaunchEngaged(); } function calcTax(address from, address to, uint amount) internal view returns (uint) { if (from == owner() || to == owner() || from == address(this)) { return 0; return amount * buyTaxBps / 10_000; return amount * sellTaxBps / 10_000; return 0; } } function calcTax(address from, address to, uint amount) internal view returns (uint) { if (from == owner() || to == owner() || from == address(this)) { return 0; return amount * buyTaxBps / 10_000; return amount * sellTaxBps / 10_000; return 0; } } } else if (from == address(pair)) { } else if (to == address(pair)) { } else { function sellCollectedTaxes() internal lockTheSwap { uint tokensForLiq = balanceOf[address(this)] / 4; uint tokensToSwap = balanceOf[address(this)] - tokensForLiq; address[] memory path = new address[](2); path[0] = address(this); path[1] = router.WETH(); router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokensToSwap, 0, path, address(this), block.timestamp ); address(this), tokensForLiq, 0, 0, owner(), block.timestamp); } router.addLiquidityETH{ value: address(this).balance }( myWallet.call{value: address(this).balance}(""); function transfer(address to, uint amount) public override returns (bool) { return transferFrom(msg.sender, to, amount); } function transferFrom( address from, address to, uint amount ) public override returns (bool) { if (from != msg.sender) { if (allowed != type(uint).max) allowance[from][msg.sender] = allowed - amount; } if (balanceOf[address(this)] > getMinSwapAmount() && !isSellingCollectedTaxes && from != address(pair) && from != address(this)) { sellCollectedTaxes(); } uint tax = calcTax(from, to, amount); uint afterTaxAmount = amount - tax; balanceOf[from] -= amount; unchecked { balanceOf[to] += afterTaxAmount; } emit Transfer(from, to, afterTaxAmount); if (tax > 0) { uint revenue = tax / 5; tax -= revenue; unchecked { balanceOf[address(this)] += tax; balanceOf[revenueWallet] += revenue; } emit Transfer(from, revenueWallet, revenue); } return true; } function transferFrom( address from, address to, uint amount ) public override returns (bool) { if (from != msg.sender) { if (allowed != type(uint).max) allowance[from][msg.sender] = allowed - amount; } if (balanceOf[address(this)] > getMinSwapAmount() && !isSellingCollectedTaxes && from != address(pair) && from != address(this)) { sellCollectedTaxes(); } uint tax = calcTax(from, to, amount); uint afterTaxAmount = amount - tax; balanceOf[from] -= amount; unchecked { balanceOf[to] += afterTaxAmount; } emit Transfer(from, to, afterTaxAmount); if (tax > 0) { uint revenue = tax / 5; tax -= revenue; unchecked { balanceOf[address(this)] += tax; balanceOf[revenueWallet] += revenue; } emit Transfer(from, revenueWallet, revenue); } return true; } function transferFrom( address from, address to, uint amount ) public override returns (bool) { if (from != msg.sender) { if (allowed != type(uint).max) allowance[from][msg.sender] = allowed - amount; } if (balanceOf[address(this)] > getMinSwapAmount() && !isSellingCollectedTaxes && from != address(pair) && from != address(this)) { sellCollectedTaxes(); } uint tax = calcTax(from, to, amount); uint afterTaxAmount = amount - tax; balanceOf[from] -= amount; unchecked { balanceOf[to] += afterTaxAmount; } emit Transfer(from, to, afterTaxAmount); if (tax > 0) { uint revenue = tax / 5; tax -= revenue; unchecked { balanceOf[address(this)] += tax; balanceOf[revenueWallet] += revenue; } emit Transfer(from, revenueWallet, revenue); } return true; } function transferFrom( address from, address to, uint amount ) public override returns (bool) { if (from != msg.sender) { if (allowed != type(uint).max) allowance[from][msg.sender] = allowed - amount; } if (balanceOf[address(this)] > getMinSwapAmount() && !isSellingCollectedTaxes && from != address(pair) && from != address(this)) { sellCollectedTaxes(); } uint tax = calcTax(from, to, amount); uint afterTaxAmount = amount - tax; balanceOf[from] -= amount; unchecked { balanceOf[to] += afterTaxAmount; } emit Transfer(from, to, afterTaxAmount); if (tax > 0) { uint revenue = tax / 5; tax -= revenue; unchecked { balanceOf[address(this)] += tax; balanceOf[revenueWallet] += revenue; } emit Transfer(from, revenueWallet, revenue); } return true; } function transferFrom( address from, address to, uint amount ) public override returns (bool) { if (from != msg.sender) { if (allowed != type(uint).max) allowance[from][msg.sender] = allowed - amount; } if (balanceOf[address(this)] > getMinSwapAmount() && !isSellingCollectedTaxes && from != address(pair) && from != address(this)) { sellCollectedTaxes(); } uint tax = calcTax(from, to, amount); uint afterTaxAmount = amount - tax; balanceOf[from] -= amount; unchecked { balanceOf[to] += afterTaxAmount; } emit Transfer(from, to, afterTaxAmount); if (tax > 0) { uint revenue = tax / 5; tax -= revenue; unchecked { balanceOf[address(this)] += tax; balanceOf[revenueWallet] += revenue; } emit Transfer(from, revenueWallet, revenue); } return true; } function transferFrom( address from, address to, uint amount ) public override returns (bool) { if (from != msg.sender) { if (allowed != type(uint).max) allowance[from][msg.sender] = allowed - amount; } if (balanceOf[address(this)] > getMinSwapAmount() && !isSellingCollectedTaxes && from != address(pair) && from != address(this)) { sellCollectedTaxes(); } uint tax = calcTax(from, to, amount); uint afterTaxAmount = amount - tax; balanceOf[from] -= amount; unchecked { balanceOf[to] += afterTaxAmount; } emit Transfer(from, to, afterTaxAmount); if (tax > 0) { uint revenue = tax / 5; tax -= revenue; unchecked { balanceOf[address(this)] += tax; balanceOf[revenueWallet] += revenue; } emit Transfer(from, revenueWallet, revenue); } return true; } emit Transfer(from, address(this), tax); function setTaxes(uint256 _buyTaxBps, uint256 _sellTaxBps) public onlyOwner { buyTaxBps = _buyTaxBps; sellTaxBps = _sellTaxBps; } }
3,670,151
[ 1, 8410, 434, 326, 2172, 14467, 716, 903, 1960, 358, 326, 511, 52, 21198, 434, 326, 2172, 14467, 716, 903, 1960, 358, 13667, 310, 1021, 5320, 358, 11140, 853, 16, 316, 10853, 3143, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 539, 38, 539, 38, 539, 353, 14223, 6914, 16, 4232, 39, 3462, 288, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 4633, 31, 203, 565, 467, 984, 291, 91, 438, 58, 22, 1733, 1071, 3272, 31, 203, 565, 467, 984, 291, 91, 438, 58, 22, 4154, 1071, 3082, 31, 203, 203, 565, 2254, 3238, 5381, 28226, 67, 13272, 23893, 273, 1728, 67, 3784, 67, 3784, 380, 1728, 636, 28, 31, 203, 203, 565, 2254, 5381, 511, 52, 67, 38, 5857, 273, 2468, 3784, 31, 203, 203, 565, 2254, 5381, 20503, 1584, 1360, 67, 38, 5857, 273, 1728, 67, 3784, 300, 511, 52, 67, 38, 5857, 31, 203, 203, 565, 2254, 1071, 30143, 7731, 38, 1121, 273, 6604, 31, 203, 565, 2254, 1071, 357, 80, 7731, 38, 1121, 273, 6604, 31, 203, 565, 1426, 11604, 1165, 310, 10808, 329, 7731, 281, 31, 203, 203, 565, 871, 18830, 77, 6522, 28429, 11349, 5621, 203, 565, 871, 18830, 77, 6522, 1669, 24688, 11349, 5621, 203, 565, 871, 7780, 4162, 9569, 28429, 11349, 5621, 203, 203, 565, 1758, 1071, 721, 332, 7637, 8924, 31, 203, 203, 565, 1426, 1071, 28601, 69, 22573, 31, 203, 203, 565, 1758, 1071, 3399, 16936, 31, 203, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 283, 24612, 16936, 31, 203, 203, 565, 1426, 1071, 24691, 11349, 12212, 31, 203, 565, 1426, 1071, 1015, 24688, 11349, 12212, 31, 203, 203, 565, 3885, 1435, 4232, 39, 3462, 2932, 38, 539, 605, 539, 605, 539, 3113, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-06-22 */ /** * SourceUnit: /Users/prateekyammanuru/work/marlin/contracts_github/Contracts/contracts/Stake/ClusterRegistry.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; } /** * SourceUnit: /Users/prateekyammanuru/work/marlin/contracts_github/Contracts/contracts/Stake/ClusterRegistry.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; } } /** * SourceUnit: /Users/prateekyammanuru/work/marlin/contracts_github/Contracts/contracts/Stake/ClusterRegistry.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); } /** * SourceUnit: /Users/prateekyammanuru/work/marlin/contracts_github/Contracts/contracts/Stake/ClusterRegistry.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; } } /** * SourceUnit: /Users/prateekyammanuru/work/marlin/contracts_github/Contracts/contracts/Stake/ClusterRegistry.sol */ pragma solidity ^0.5.0; ////import "@openzeppelin/upgrades/contracts/Initializable.sol"; ////import "../../GSN/Context.sol"; ////import "./IERC20.sol"; ////import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } uint256[50] private ______gap; } /** * SourceUnit: /Users/prateekyammanuru/work/marlin/contracts_github/Contracts/contracts/Stake/ClusterRegistry.sol */ pragma solidity ^0.5.0; ////import "@openzeppelin/upgrades/contracts/Initializable.sol"; ////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 aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _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; } uint256[50] private ______gap; } /** * SourceUnit: /Users/prateekyammanuru/work/marlin/contracts_github/Contracts/contracts/Stake/ClusterRegistry.sol */ pragma solidity >=0.4.21 <0.7.0; contract ClusterRegistry is Initializable, Ownable { using SafeMath for uint256; uint256 constant UINT256_MAX = ~uint256(0); struct Cluster { uint256 commission; address rewardAddress; address clientKey; bytes32 networkId; // keccak256("ETH") // token ticker for anyother chain in place of ETH Status status; } struct Lock { uint256 unlockBlock; uint256 iValue; } mapping(address => Cluster) clusters; mapping(bytes32 => Lock) public locks; mapping(bytes32 => uint256) public lockWaitTime; bytes32 constant COMMISSION_LOCK_SELECTOR = keccak256("COMMISSION_LOCK"); bytes32 constant SWITCH_NETWORK_LOCK_SELECTOR = keccak256("SWITCH_NETWORK_LOCK"); bytes32 constant UNREGISTER_LOCK_SELECTOR = keccak256("UNREGISTER_LOCK"); enum Status{NOT_REGISTERED, REGISTERED} mapping(address => address) public clientKeys; event ClusterRegistered( address cluster, bytes32 networkId, uint256 commission, address rewardAddress, address clientKey ); event CommissionUpdateRequested(address cluster, uint256 commissionAfterUpdate, uint256 effectiveBlock); event CommissionUpdated(address cluster, uint256 updatedCommission, uint256 updatedAt); event RewardAddressUpdated(address cluster, address updatedRewardAddress); event NetworkSwitchRequested(address cluster, bytes32 networkId, uint256 effectiveBlock); event NetworkSwitched(address cluster, bytes32 networkId, uint256 updatedAt); event ClientKeyUpdated(address cluster, address clientKey); event ClusterUnregisterRequested(address cluster, uint256 effectiveBlock); event ClusterUnregistered(address cluster, uint256 updatedAt); event LockTimeUpdated(bytes32 selector, uint256 prevLockTime, uint256 updatedLockTime); function initialize(bytes32[] memory _selectors, uint256[] memory _lockWaitTimes, address _owner) public initializer { require( _selectors.length == _lockWaitTimes.length, "CR:I-Invalid params" ); for(uint256 i=0; i < _selectors.length; i++) { lockWaitTime[_selectors[i]] = _lockWaitTimes[i]; emit LockTimeUpdated(_selectors[i], 0, _lockWaitTimes[i]); } super.initialize(_owner); } function updateLockWaitTime(bytes32 _selector, uint256 _updatedWaitTime) external onlyOwner { emit LockTimeUpdated(_selector, lockWaitTime[_selector], _updatedWaitTime); lockWaitTime[_selector] = _updatedWaitTime; } function register( bytes32 _networkId, uint256 _commission, address _rewardAddress, address _clientKey ) external returns(bool) { // This happens only when the data of the cluster is registered or it wasn't registered before require( !isClusterValid(msg.sender), "CR:R-Cluster is already registered" ); require(_commission <= 100, "CR:R-Commission more than 100%"); require(clientKeys[_clientKey] == address(0), "CR:R - Client key is already used"); clusters[msg.sender].commission = _commission; clusters[msg.sender].rewardAddress = _rewardAddress; clusters[msg.sender].clientKey = _clientKey; clusters[msg.sender].networkId = _networkId; clusters[msg.sender].status = Status.REGISTERED; clientKeys[_clientKey] = msg.sender; emit ClusterRegistered(msg.sender, _networkId, _commission, _rewardAddress, _clientKey); } function updateCluster(uint256 _commission, bytes32 _networkId, address _rewardAddress, address _clientKey) public { if(_networkId != bytes32(0)) { switchNetwork(_networkId); } if(_rewardAddress != address(0)) { updateRewardAddress(_rewardAddress); } if(_clientKey != address(0)) { updateClientKey(_clientKey); } if(_commission != UINT256_MAX) { updateCommission(_commission); } } function updateCommission(uint256 _commission) public { require( isClusterValid(msg.sender), "CR:UCM-Cluster not registered" ); require(_commission <= 100, "CR:UCM-Commission more than 100%"); bytes32 lockId = keccak256(abi.encodePacked(COMMISSION_LOCK_SELECTOR, msg.sender)); uint256 unlockBlock = locks[lockId].unlockBlock; require( unlockBlock < block.number, "CR:UCM-Commission update in progress" ); if(unlockBlock != 0) { uint256 currentCommission = locks[lockId].iValue; clusters[msg.sender].commission = currentCommission; emit CommissionUpdated(msg.sender, currentCommission, unlockBlock); } uint256 updatedUnlockBlock = block.number.add(lockWaitTime[COMMISSION_LOCK_SELECTOR]); locks[lockId] = Lock(updatedUnlockBlock, _commission); emit CommissionUpdateRequested(msg.sender, _commission, updatedUnlockBlock); } function switchNetwork(bytes32 _networkId) public { require( isClusterValid(msg.sender), "CR:SN-Cluster not registered" ); bytes32 lockId = keccak256(abi.encodePacked(SWITCH_NETWORK_LOCK_SELECTOR, msg.sender)); uint256 unlockBlock = locks[lockId].unlockBlock; require( unlockBlock < block.number, "CR:SN-Network switch in progress" ); if(unlockBlock != 0) { bytes32 currentNetwork = bytes32(locks[lockId].iValue); clusters[msg.sender].networkId = currentNetwork; emit NetworkSwitched(msg.sender, currentNetwork, unlockBlock); } uint256 updatedUnlockBlock = block.number.add(lockWaitTime[SWITCH_NETWORK_LOCK_SELECTOR]); locks[lockId] = Lock(updatedUnlockBlock, uint256(_networkId)); emit NetworkSwitchRequested(msg.sender, _networkId, updatedUnlockBlock); } function updateRewardAddress(address _rewardAddress) public { require( isClusterValid(msg.sender), "CR:URA-Cluster not registered" ); clusters[msg.sender].rewardAddress = _rewardAddress; emit RewardAddressUpdated(msg.sender, _rewardAddress); } function updateClientKey(address _clientKey) public { // TODO: Add delay to client key updates as well require( isClusterValid(msg.sender), "CR:UCK-Cluster not registered" ); require(clientKeys[_clientKey] == address(0), "CR:UCK - Client key is already used"); delete clientKeys[clusters[msg.sender].clientKey]; clusters[msg.sender].clientKey = _clientKey; clientKeys[_clientKey] = msg.sender; emit ClientKeyUpdated(msg.sender, _clientKey); } function unregister() external { require( clusters[msg.sender].status != Status.NOT_REGISTERED, "CR:UR-Cluster not registered" ); bytes32 lockId = keccak256(abi.encodePacked(UNREGISTER_LOCK_SELECTOR, msg.sender)); uint256 unlockBlock = locks[lockId].unlockBlock; require( unlockBlock < block.number, "CR:UR-Unregistration already in progress" ); if(unlockBlock != 0) { clusters[msg.sender].status = Status.NOT_REGISTERED; emit ClusterUnregistered(msg.sender, unlockBlock); delete clientKeys[clusters[msg.sender].clientKey]; delete locks[lockId]; delete locks[keccak256(abi.encodePacked(COMMISSION_LOCK_SELECTOR, msg.sender))]; delete locks[keccak256(abi.encodePacked(SWITCH_NETWORK_LOCK_SELECTOR, msg.sender))]; return; } uint256 updatedUnlockBlock = block.number.add(lockWaitTime[UNREGISTER_LOCK_SELECTOR]); locks[lockId] = Lock(updatedUnlockBlock, 0); emit ClusterUnregisterRequested(msg.sender, updatedUnlockBlock); } function isClusterValid(address _cluster) public returns(bool) { bytes32 lockId = keccak256(abi.encodePacked(UNREGISTER_LOCK_SELECTOR, _cluster)); uint256 unlockBlock = locks[lockId].unlockBlock; if(unlockBlock != 0 && unlockBlock < block.number) { clusters[_cluster].status = Status.NOT_REGISTERED; delete clientKeys[clusters[_cluster].clientKey]; emit ClusterUnregistered(_cluster, unlockBlock); delete locks[lockId]; delete locks[keccak256(abi.encodePacked(COMMISSION_LOCK_SELECTOR, msg.sender))]; delete locks[keccak256(abi.encodePacked(SWITCH_NETWORK_LOCK_SELECTOR, msg.sender))]; return false; } return (clusters[_cluster].status != Status.NOT_REGISTERED); // returns true if the status is registered } function getCommission(address _cluster) public returns(uint256) { bytes32 lockId = keccak256(abi.encodePacked(COMMISSION_LOCK_SELECTOR, _cluster)); uint256 unlockBlock = locks[lockId].unlockBlock; if(unlockBlock != 0 && unlockBlock < block.number) { uint256 currentCommission = locks[lockId].iValue; clusters[_cluster].commission = currentCommission; emit CommissionUpdated(_cluster, currentCommission, unlockBlock); delete locks[lockId]; return currentCommission; } return clusters[_cluster].commission; } function getNetwork(address _cluster) public returns(bytes32) { bytes32 lockId = keccak256(abi.encodePacked(SWITCH_NETWORK_LOCK_SELECTOR, _cluster)); uint256 unlockBlock = locks[lockId].unlockBlock; if(unlockBlock != 0 && unlockBlock < block.number) { bytes32 currentNetwork = bytes32(locks[lockId].iValue); clusters[msg.sender].networkId = currentNetwork; emit NetworkSwitched(msg.sender, currentNetwork, unlockBlock); delete locks[lockId]; return currentNetwork; } return clusters[_cluster].networkId; } function getRewardAddress(address _cluster) external view returns(address) { return clusters[_cluster].rewardAddress; } function getClientKey(address _cluster) external view returns(address) { return clusters[_cluster].clientKey; } function getCluster(address _cluster) external returns( uint256 commission, address rewardAddress, address clientKey, bytes32 networkId, bool isValidCluster ) { return ( getCommission(_cluster), clusters[_cluster].rewardAddress, clusters[_cluster].clientKey, getNetwork(_cluster), isClusterValid(_cluster) ); } function getRewardInfo(address _cluster) external returns(uint256, address) { return (getCommission(_cluster), clusters[_cluster].rewardAddress); } function addClientKeys(address[] calldata _clusters) external onlyOwner { for(uint256 i=0; i < _clusters.length; i++) { address _clientKey = clusters[_clusters[i]].clientKey; require(_clientKey != address(0), "CR:ACK - Cluster has invalid client key"); clientKeys[_clientKey] = _clusters[i]; } } }
* @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be aplied to your functions to restrict their use to the owner./
contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return _msgSender() == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; }
14,976,589
[ 1, 8924, 1605, 1492, 8121, 279, 5337, 2006, 3325, 12860, 16, 1625, 1915, 353, 392, 2236, 261, 304, 3410, 13, 716, 848, 506, 17578, 12060, 2006, 358, 2923, 4186, 18, 1220, 1605, 353, 1399, 3059, 16334, 18, 2597, 903, 1221, 2319, 326, 9606, 1375, 3700, 5541, 9191, 1492, 848, 506, 279, 3110, 358, 3433, 4186, 358, 13108, 3675, 999, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 6914, 353, 10188, 6934, 16, 1772, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 2398, 203, 203, 203, 565, 445, 4046, 12, 2867, 5793, 13, 1071, 12562, 288, 203, 3639, 389, 8443, 273, 5793, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 389, 8443, 1769, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 291, 5541, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 353, 5541, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 3576, 12021, 1435, 422, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 1338, 5541, 288, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 3639, 389, 8443, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 5460, 12565, 12, 2867, 394, 5541, 13, 2713, 288, 203, 3639, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 2 ]
/* Introducing "TORPEDO LAUNCH" our second HDX20 POWERED GAME running on the Ethereum Blockchain "TORPEDO LAUNCH" is playable @ https://torpedolaunch.io About the game : TORPEDO LAUNCH is a Submarine Arcade action game where the player is launching torpedoes to sink enemies boats How to play TORPEDO LAUNCH: The Campaign will start after at least 1 player has played and submitted a score to the worldwide leaderboard then, for every new highscore registered, a 24H countdown will reset. At the end of the countdown, the 8 best players ranked on the leaderboard will share the Treasure proportionally to their scores and everybody will receive their payout. Every time you buy new torpedoes, 5% of the price will buy you HDX20 Token earning you Ethereum from the volume of any HDX20 POWERED GAMES (visit https://hdx20.io for details) while 20% of the price will buy you new shares of the game. Please remember, at every new buy, the price of the share is increasing a little and so will be your payout even if you are not a winner therefore buying shares at the beginning of the campaign is highly advised. You can withdraw any owned amount at all time during the game. Play for the big WIN, Play for the TREASURE, Play for staking HDX20 TOKEN or Play for all at once...Your Choice! We wish you Good Luck! PAYOUTS DISTRIBUTION: .60% to the winners of the race distributed proportionally to their score if ranked from 1st to 8th. .25% to the community of HDX20 gamers/holders distributed as price appreciation. .5% to developer for running, developing and expanding the platform. .10% for provisioning the TREASURE for the next Campaign. This product is copyrighted. Any unauthorized copy, modification, or use without express written consent from HyperDevbox is prohibited. Copyright 2018 HyperDevbox */ pragma solidity ^0.4.25; interface HDX20Interface { function() payable external; function buyTokenFromGame( address _customerAddress , address _referrer_address ) payable external returns(uint256); function payWithToken( uint256 _eth , address _player_address ) external returns(uint256); function appreciateTokenPrice() payable external; function totalSupply() external view returns(uint256); function ethBalanceOf(address _customerAddress) external view returns(uint256); function balanceOf(address _playerAddress) external view returns(uint256); function sellingPrice( bool includeFees) external view returns(uint256); } contract TorpedoLaunchGame { HDX20Interface private HDXcontract = HDX20Interface(0x8942a5995bd168f347f7ec58f25a54a9a064f882); using SafeMath for uint256; using SafeMath128 for uint128; /*============================== = EVENTS = ==============================*/ event OwnershipTransferred( address previousOwner, address nextOwner, uint256 timeStamp ); event HDXcontractChanged( address previous, address next, uint256 timeStamp ); event onWithdrawGains( address customerAddress, uint256 ethereumWithdrawn, uint256 timeStamp ); event onNewScore( uint256 gRND, uint256 blockNumberTimeout, uint256 score, address customerAddress, bool newHighScore, bool highscoreChanged ); event onNewCampaign( uint256 gRND, uint256 blockNumber ); event onBuyTorpedo( address customerAddress, uint256 gRND, uint256 torpedoBatchID, uint256 torpedoBatchBlockTimeout, uint256 nbToken, uint32 torpedoBatchMultiplier //x1, x10, x100 ); event onMaintenance( bool mode, uint256 timeStamp ); event onCloseEntry( uint256 gRND ); event onChangeBlockTimeAverage( uint256 blocktimeavg ); event onChangeMinimumPrice( uint256 minimum, uint256 timeStamp ); event onNewName( address customerAddress, bytes32 name, uint256 timeStamp ); /*============================== = MODIFIERS = ==============================*/ modifier onlyOwner { require (msg.sender == owner ); _; } modifier onlyFromHDXToken { require (msg.sender == address( HDXcontract )); _; } modifier onlyDirectTransaction { require (msg.sender == tx.origin); _; } modifier isPlayer { require (PlayerData[ msg.sender].gRND !=0); _; } modifier isMaintenance { require (maintenanceMode==true); _; } modifier isNotMaintenance { require (maintenanceMode==false); _; } address public owner; address public signerAuthority = 0xf77444cE64f3F46ba6b63F6b9411dF9c589E3319; constructor () public { owner = msg.sender; if ( address(this).balance > 0) { owner.transfer( address(this).balance ); } } function changeOwner(address _nextOwner) public onlyOwner { require (_nextOwner != owner); require(_nextOwner != address(0)); emit OwnershipTransferred(owner, _nextOwner , now); owner = _nextOwner; } function changeSigner(address _nextSigner) public onlyOwner { require (_nextSigner != signerAuthority); require(_nextSigner != address(0)); signerAuthority = _nextSigner; } function changeHDXcontract(address _next) public onlyOwner { require (_next != address( HDXcontract )); require( _next != address(0)); emit HDXcontractChanged(address(HDXcontract), _next , now); HDXcontract = HDX20Interface( _next); } function changeBlockTimeAverage( uint256 blocktimeavg) public onlyOwner { require ( blocktimeavg>0 ); blockTimeAverage = blocktimeavg; emit onChangeBlockTimeAverage( blockTimeAverage ); } function enableMaintenance() public onlyOwner { maintenanceMode = true; emit onMaintenance( maintenanceMode , now); } function disableMaintenance() public onlyOwner { maintenanceMode = false; emit onMaintenance( maintenanceMode , now); initCampaign(); } function changeMinimumPrice( uint256 newmini) public onlyOwner { if (newmini>0) { minimumSharePrice = newmini; } emit onChangeMinimumPrice( newmini , now ); } /*================================ = GAMES VARIABLES = ================================*/ struct PlayerData_s { uint256 chest; uint256 payoutsTo; uint256 gRND; } struct PlayerGameRound_s { uint256 shares; uint256 torpedoBatchID; //0==no torpedo, otherwise uint256 torpedoBatchBlockTimeout; bytes data; uint128 token; uint32[3] packedData; //[0] = torpedomultiplier //[1] = playerID //[2]=score } struct GameRoundData_s { uint256 blockNumber; uint256 blockNumberTimeout; uint256 sharePrice; uint256 sharePots; uint256 shareEthBalance; uint256 shareSupply; uint256 treasureSupply; mapping (uint32 => address) IDtoAddress; uint256 hdx20AppreciationPayout; uint256 devAppreciationPayout; //******************************************************************************************** uint32[16] highscorePool; //[0-7] == uint32 score //[8-15] == uint32 playerID uint32[2] extraData;//[0]==this_TurnRound , [1]== totalPlayers } mapping (address => PlayerData_s) private PlayerData; mapping (address => mapping (uint256 => PlayerGameRound_s)) private PlayerGameRound; mapping (uint256 => GameRoundData_s) private GameRoundData; mapping( address => bytes32) private registeredNames; bool private maintenanceMode=false; uint256 private this_gRND =0; //85 , missing 15% for shares appreciation eg:share price increase uint8 constant private HDX20BuyFees = 5; uint8 constant private TREASUREBuyFees = 60; uint8 constant private BUYPercentage = 20; uint8 constant private DevFees = 5; uint8 constant private TreasureFees = 10; uint8 constant private AppreciationFees = 25; uint256 constant internal magnitude = 1e18; uint256 private genTreasure = 0; uint256 private minimumSharePrice = 0.01 ether; uint256 private blockTimeAverage = 15; //seconds per block /*================================ = PUBLIC FUNCTIONS = ================================*/ //fallback will be called only from the HDX token contract to fund the game from customers's HDX20 function() payable public onlyFromHDXToken { } function ChargeTreasure() public payable { genTreasure = SafeMath.add( genTreasure , msg.value); } function buyTreasureShares(GameRoundData_s storage _GameRoundData , uint256 _eth ) private returns( uint256) { uint256 _nbshares = (_eth.mul( magnitude)) / _GameRoundData.sharePrice; _GameRoundData.treasureSupply = _GameRoundData.treasureSupply.add( _nbshares ); _GameRoundData.shareSupply = _GameRoundData.shareSupply.add( _nbshares ); return( _nbshares); } function initCampaign() public onlyOwner isNotMaintenance { this_gRND++; GameRoundData_s storage _GameRoundData = GameRoundData[ this_gRND ]; _GameRoundData.blockNumber = block.number; _GameRoundData.blockNumberTimeout = block.number + (360*10*24*3600); uint256 _sharePrice = minimumSharePrice; _GameRoundData.sharePrice = _sharePrice; uint256 _nbshares = buyTreasureShares(_GameRoundData, genTreasure ); //convert into ETH _nbshares = _nbshares.mul( _sharePrice ) / magnitude; //start balance _GameRoundData.shareEthBalance = _nbshares; genTreasure = genTreasure.sub( _nbshares); emit onNewCampaign( this_gRND , block.number); } function get_TotalPayout( GameRoundData_s storage _GameRoundData ) private view returns( uint256) { uint256 _payout = 0; uint256 _sharePrice = _GameRoundData.sharePrice; uint256 _bet = _GameRoundData.sharePots; _payout = _payout.add( _bet.mul (_sharePrice) / magnitude ); uint256 _potValue = ((_GameRoundData.treasureSupply.mul( _sharePrice ) / magnitude).mul(100-DevFees-TreasureFees-AppreciationFees)) / 100; _payout = _payout.add( _potValue ); return( _payout ); } function get_PendingGains( address _player_address , uint256 _gRND) private view returns( uint256) { //did not play if (PlayerData[ _player_address].gRND != _gRND || _gRND==0) return( 0 ); GameRoundData_s storage _GameRoundData = GameRoundData[ _gRND ]; // uint32 _winner = _GameRoundData.extraData[1]; uint256 _gains = 0; uint256 _sharePrice = _GameRoundData.sharePrice; uint256 _shares; PlayerGameRound_s storage _PlayerGameRound = PlayerGameRound[ _player_address][_gRND]; _shares = _PlayerGameRound.shares; _gains = _gains.add( _shares.mul( _sharePrice) / magnitude ); //if the race payment is made (race is over) then we add also the winner prize if (_GameRoundData.extraData[0] >= (1<<30)) { uint256 _score = 0; uint256 _totalscore = 0; uint256 _treasure = ((_GameRoundData.treasureSupply.mul( _sharePrice ) / magnitude).mul(100-DevFees-TreasureFees-AppreciationFees)) / 100; for( uint i=0;i<8;i++) { _totalscore = _totalscore.add( uint256(_GameRoundData.highscorePool[i])); if (_GameRoundData.highscorePool[8+i]==_PlayerGameRound.packedData[1]) { _score = uint256(_GameRoundData.highscorePool[i]); } } if (_totalscore>0) _gains = _gains.add( _treasure.mul( _score) / _totalscore ); } return( _gains ); } //only for the Result Data Screen on the game not used for the payout function get_PendingGainsAll( address _player_address , uint256 _gRND) private view returns( uint256) { //did not play if (PlayerData[ _player_address].gRND != _gRND || _gRND==0) return( 0 ); GameRoundData_s storage _GameRoundData = GameRoundData[ _gRND ]; // uint32 _winner = _GameRoundData.extraData[1]; uint256 _gains = 0; uint256 _sharePrice = _GameRoundData.sharePrice; uint256 _shares; PlayerGameRound_s storage _PlayerGameRound = PlayerGameRound[ _player_address][_gRND]; _shares = _PlayerGameRound.shares; _gains = _gains.add( _shares.mul( _sharePrice) / magnitude ); { uint256 _score = 0; uint256 _totalscore = 0; uint256 _treasure = ((_GameRoundData.treasureSupply.mul( _sharePrice ) / magnitude).mul(100-DevFees-TreasureFees-AppreciationFees)) / 100; for( uint i=0;i<8;i++) { _totalscore = _totalscore.add( uint256(_GameRoundData.highscorePool[i])); if (_GameRoundData.highscorePool[8+i]==_PlayerGameRound.packedData[1]) { _score = uint256(_GameRoundData.highscorePool[i]); } } if (_totalscore>0) _gains = _gains.add( _treasure.mul( _score) / _totalscore ); } return( _gains ); } //process streaming HDX20 appreciation and dev fees appreciation function process_sub_Taxes( GameRoundData_s storage _GameRoundData , uint256 minimum) private { uint256 _sharePrice = _GameRoundData.sharePrice; uint256 _potValue = _GameRoundData.treasureSupply.mul( _sharePrice ) / magnitude; uint256 _appreciation = SafeMath.mul( _potValue , AppreciationFees) / 100; uint256 _dev = SafeMath.mul( _potValue , DevFees) / 100; if (_dev > _GameRoundData.devAppreciationPayout) { _dev -= _GameRoundData.devAppreciationPayout; if (_dev>minimum) { _GameRoundData.devAppreciationPayout = _GameRoundData.devAppreciationPayout.add( _dev ); HDXcontract.buyTokenFromGame.value( _dev )( owner , address(0)); } } if (_appreciation> _GameRoundData.hdx20AppreciationPayout) { _appreciation -= _GameRoundData.hdx20AppreciationPayout; if (_appreciation>minimum) { _GameRoundData.hdx20AppreciationPayout = _GameRoundData.hdx20AppreciationPayout.add( _appreciation ); HDXcontract.appreciateTokenPrice.value( _appreciation )(); } } } //process the fees, hdx20 appreciation, calcul results at the end of the race function process_Taxes( GameRoundData_s storage _GameRoundData ) private { uint32 turnround = _GameRoundData.extraData[0]; if (turnround>0 && turnround<(1<<30)) { _GameRoundData.extraData[0] = turnround | (1<<30); uint256 _sharePrice = _GameRoundData.sharePrice; uint256 _potValue = _GameRoundData.treasureSupply.mul( _sharePrice ) / magnitude; uint256 _treasure = SafeMath.mul( _potValue , TreasureFees) / 100; genTreasure = genTreasure.add( _treasure ); //take care of any left over process_sub_Taxes( _GameRoundData , 0); } } function ValidTorpedoScore( int256 score, uint256 torpedoBatchID , bytes32 r , bytes32 s , uint8 v) public onlyDirectTransaction { address _customer_address = msg.sender; require( maintenanceMode==false && this_gRND>0 && (block.number <GameRoundData[ this_gRND ].blockNumberTimeout) && (PlayerData[ _customer_address].gRND == this_gRND)); GameVar_s memory gamevar; gamevar.score = score; gamevar.torpedoBatchID = torpedoBatchID; gamevar.r = r; gamevar.s = s; gamevar.v = v; coreValidTorpedoScore( _customer_address , gamevar ); } struct GameVar_s { bool madehigh; bool highscoreChanged; uint max_score; uint min_score; uint min_score_index; uint max_score_index; uint our_score_index; uint32 max_score_pid; uint32 multiplier; uint256 torpedoBatchID; int256 score; bytes32 r; bytes32 s; uint8 v; } function coreValidTorpedoScore( address _player_address , GameVar_s gamevar) private { PlayerGameRound_s storage _PlayerGameRound = PlayerGameRound[ _player_address][ this_gRND]; GameRoundData_s storage _GameRoundData = GameRoundData[ this_gRND ]; require((gamevar.torpedoBatchID != 0) && (gamevar.torpedoBatchID== _PlayerGameRound.torpedoBatchID)); gamevar.madehigh = false; gamevar.highscoreChanged = false; // gamevar.max_score = 0; gamevar.min_score = 0xffffffff; // gamevar.min_score_index = 0; // gamevar.max_score_index = 0; // gamevar.our_score_index = 0; if (block.number>=_PlayerGameRound.torpedoBatchBlockTimeout || (ecrecover(keccak256(abi.encodePacked( gamevar.score,gamevar.torpedoBatchID )) , gamevar.v, gamevar.r, gamevar.s) != signerAuthority)) { gamevar.score = 0; } int256 tempo = int256(_PlayerGameRound.packedData[2]) + (gamevar.score * int256(_PlayerGameRound.packedData[0])); if (tempo<0) tempo = 0; if (tempo>0xffffffff) tempo = 0xffffffff; uint256 p_score = uint256( tempo ); //store the player score _PlayerGameRound.packedData[2] = uint32(p_score); for(uint i=0;i<8;i++) { uint ss = _GameRoundData.highscorePool[i]; if (ss>gamevar.max_score) { gamevar.max_score = ss; gamevar.max_score_index =i; } if (ss<gamevar.min_score) { gamevar.min_score = ss; gamevar.min_score_index = i; } //are we in the pool already if (_GameRoundData.highscorePool[8+i]==_PlayerGameRound.packedData[1]) gamevar.our_score_index=1+i; } //grab current player id highscore before we potentially overwrite it gamevar.max_score_pid = _GameRoundData.highscorePool[ 8+gamevar.max_score_index]; //at first if we are in the pool simply update our score if (gamevar.our_score_index>0) { _GameRoundData.highscorePool[ gamevar.our_score_index -1] = uint32(p_score); gamevar.highscoreChanged = true; } else { //we were not in the pool, are we more than the minimum score if (p_score > gamevar.min_score) { //yes the minimum should go away and we should replace it in the pool _GameRoundData.highscorePool[ gamevar.min_score_index ] =uint32(p_score); _GameRoundData.highscorePool[ 8+gamevar.min_score_index] = _PlayerGameRound.packedData[1]; //put our playerID gamevar.highscoreChanged = true; } } //new highscore ? if (p_score>gamevar.max_score) { //yes //same person if ( gamevar.max_score_pid != _PlayerGameRound.packedData[1] ) { //no so reset the counter _GameRoundData.blockNumberTimeout = block.number + ((24*60*60) / blockTimeAverage); _GameRoundData.extraData[0]++; // new turn gamevar.madehigh = true; } } //ok reset it so we can get a new one _PlayerGameRound.torpedoBatchID = 0; emit onNewScore( this_gRND , _GameRoundData.blockNumberTimeout , p_score , _player_address , gamevar.madehigh , gamevar.highscoreChanged ); } function BuyTorpedoWithDividends( uint256 eth , int256 score, uint256 torpedoBatchID, address _referrer_address , bytes32 r , bytes32 s , uint8 v) public onlyDirectTransaction { require( maintenanceMode==false && this_gRND>0 && (eth==minimumSharePrice || eth==minimumSharePrice*10 || eth==minimumSharePrice*100) && (block.number <GameRoundData[ this_gRND ].blockNumberTimeout) ); address _customer_address = msg.sender; GameVar_s memory gamevar; gamevar.score = score; gamevar.torpedoBatchID = torpedoBatchID; gamevar.r = r; gamevar.s = s; gamevar.v = v; gamevar.multiplier =uint32( eth / minimumSharePrice); eth = HDXcontract.payWithToken( eth , _customer_address ); require( eth>0 ); CoreBuyTorpedo( _customer_address , eth , _referrer_address , gamevar ); } function BuyName( bytes32 name ) public payable { address _customer_address = msg.sender; uint256 eth = msg.value; require( maintenanceMode==false && (eth==minimumSharePrice*10)); //50% for the community //50% for the developer account eth /= 2; HDXcontract.buyTokenFromGame.value( eth )( owner , address(0)); HDXcontract.appreciateTokenPrice.value( eth )(); registeredNames[ _customer_address ] = name; emit onNewName( _customer_address , name , now ); } function BuyTorpedo( int256 score, uint256 torpedoBatchID, address _referrer_address , bytes32 r , bytes32 s , uint8 v ) public payable onlyDirectTransaction { address _customer_address = msg.sender; uint256 eth = msg.value; require( maintenanceMode==false && this_gRND>0 && (eth==minimumSharePrice || eth==minimumSharePrice*10 || eth==minimumSharePrice*100) && (block.number <GameRoundData[ this_gRND ].blockNumberTimeout)); GameVar_s memory gamevar; gamevar.score = score; gamevar.torpedoBatchID = torpedoBatchID; gamevar.r = r; gamevar.s = s; gamevar.v = v; gamevar.multiplier =uint32( eth / minimumSharePrice); CoreBuyTorpedo( _customer_address , eth , _referrer_address, gamevar); } /*================================ = CORE BUY FUNCTIONS = ================================*/ function CoreBuyTorpedo( address _player_address , uint256 eth , address _referrer_address , GameVar_s gamevar) private { PlayerGameRound_s storage _PlayerGameRound = PlayerGameRound[ _player_address][ this_gRND]; GameRoundData_s storage _GameRoundData = GameRoundData[ this_gRND ]; if (PlayerData[ _player_address].gRND != this_gRND) { if (PlayerData[_player_address].gRND !=0) { uint256 _gains = get_PendingGains( _player_address , PlayerData[ _player_address].gRND ); PlayerData[ _player_address].chest = PlayerData[ _player_address].chest.add( _gains); } PlayerData[ _player_address ].gRND = this_gRND; //player++ _GameRoundData.extraData[ 1 ]++; //a crude playerID _PlayerGameRound.packedData[1] = _GameRoundData.extraData[ 1 ]; //only to display the highscore table on the client _GameRoundData.IDtoAddress[ _GameRoundData.extraData[1] ] = _player_address; } //we need to validate the score before buying a torpedo batch if (gamevar.torpedoBatchID !=0 || _PlayerGameRound.torpedoBatchID !=0) { coreValidTorpedoScore( _player_address , gamevar); } _PlayerGameRound.packedData[0] = gamevar.multiplier; _PlayerGameRound.torpedoBatchBlockTimeout = block.number + ((4*3600) / blockTimeAverage); _PlayerGameRound.torpedoBatchID = uint256((keccak256(abi.encodePacked( block.number, _player_address , address(this))))); //HDX20BuyFees uint256 _tempo = (eth.mul(HDX20BuyFees)) / 100; _GameRoundData.shareEthBalance = _GameRoundData.shareEthBalance.add( eth-_tempo ); //minus the hdx20 fees uint256 _nb_token = HDXcontract.buyTokenFromGame.value( _tempo )( _player_address , _referrer_address); _PlayerGameRound.token += uint128(_nb_token); buyTreasureShares(_GameRoundData , (eth.mul(TREASUREBuyFees)) / 100 ); eth = eth.mul( BUYPercentage) / 100; uint256 _nbshare = (eth.mul( magnitude)) / _GameRoundData.sharePrice; _GameRoundData.shareSupply = _GameRoundData.shareSupply.add( _nbshare ); _GameRoundData.sharePots = _GameRoundData.sharePots.add( _nbshare); _PlayerGameRound.shares = _PlayerGameRound.shares.add( _nbshare); if (_GameRoundData.shareSupply>magnitude) { _GameRoundData.sharePrice = (_GameRoundData.shareEthBalance.mul( magnitude)) / _GameRoundData.shareSupply; } //HDX20 streaming appreciation process_sub_Taxes( _GameRoundData , 0.1 ether); emit onBuyTorpedo( _player_address, this_gRND, _PlayerGameRound.torpedoBatchID , _PlayerGameRound.torpedoBatchBlockTimeout, _nb_token, _PlayerGameRound.packedData[0]); } function get_Gains(address _player_address) private view returns( uint256) { uint256 _gains = PlayerData[ _player_address ].chest.add( get_PendingGains( _player_address , PlayerData[ _player_address].gRND ) ); if (_gains > PlayerData[ _player_address].payoutsTo) { _gains -= PlayerData[ _player_address].payoutsTo; } else _gains = 0; return( _gains ); } function WithdrawGains() public isPlayer { address _customer_address = msg.sender; uint256 _gains = get_Gains( _customer_address ); require( _gains>0); PlayerData[ _customer_address ].payoutsTo = PlayerData[ _customer_address ].payoutsTo.add( _gains ); emit onWithdrawGains( _customer_address , _gains , now); _customer_address.transfer( _gains ); } function CloseEntry() public onlyOwner isNotMaintenance { GameRoundData_s storage _GameRoundData = GameRoundData[ this_gRND ]; process_Taxes( _GameRoundData); emit onCloseEntry( this_gRND ); } /*================================ = VIEW AND HELPERS FUNCTIONS = ================================*/ function view_get_Treasure() public view returns(uint256) { return( genTreasure); } function view_get_gameData() public view returns( uint256 sharePrice, uint256 sharePots, uint256 shareSupply , uint256 shareEthBalance, uint32 totalPlayers , uint256 shares ,uint256 treasureSupply , uint256 torpedoBatchID , uint32 torpedoBatchMultiplier , uint256 torpedoBatchBlockTimeout , uint256 score ) { address _player_address = msg.sender; sharePrice = GameRoundData[ this_gRND].sharePrice; sharePots = GameRoundData[ this_gRND].sharePots; shareSupply = GameRoundData[ this_gRND].shareSupply; shareEthBalance = GameRoundData[ this_gRND].shareEthBalance; treasureSupply = GameRoundData[ this_gRND].treasureSupply; totalPlayers = GameRoundData[ this_gRND].extraData[1]; shares = PlayerGameRound[_player_address][this_gRND].shares; torpedoBatchID = PlayerGameRound[_player_address][this_gRND].torpedoBatchID; torpedoBatchMultiplier = PlayerGameRound[_player_address][this_gRND].packedData[0]; torpedoBatchBlockTimeout = PlayerGameRound[_player_address][this_gRND].torpedoBatchBlockTimeout; score = PlayerGameRound[_player_address][this_gRND].packedData[2]; } function view_get_gameTorpedoData() public view returns( uint256 torpedoBatchID , uint32 torpedoBatchMultiplier , uint256 torpedoBatchBlockTimeout , uint256 score ) { address _player_address = msg.sender; torpedoBatchID = PlayerGameRound[_player_address][this_gRND].torpedoBatchID; torpedoBatchMultiplier = PlayerGameRound[_player_address][this_gRND].packedData[0]; torpedoBatchBlockTimeout = PlayerGameRound[_player_address][this_gRND].torpedoBatchBlockTimeout; score = PlayerGameRound[_player_address][this_gRND].packedData[2]; } function view_get_gameHighScores() public view returns( uint32[8] highscores , address[8] addresses , bytes32[8] names ) { address _player_address = msg.sender; uint32[8] memory highscoresm; address[8] memory addressesm; bytes32[8] memory namesm; for(uint i =0;i<8;i++) { highscoresm[i] = GameRoundData[ this_gRND].highscorePool[i]; uint32 id = GameRoundData[ this_gRND].highscorePool[8+i]; addressesm[i] = GameRoundData[ this_gRND ].IDtoAddress[ id ]; namesm[i] = view_get_registeredNames( addressesm[i ]); } highscores = highscoresm; addresses = addressesm; names = namesm; } function view_get_Gains() public view returns( uint256 gains) { address _player_address = msg.sender; uint256 _gains = PlayerData[ _player_address ].chest.add( get_PendingGains( _player_address , PlayerData[ _player_address].gRND) ); if (_gains > PlayerData[ _player_address].payoutsTo) { _gains -= PlayerData[ _player_address].payoutsTo; } else _gains = 0; return( _gains ); } function view_get_gameStates() public view returns(uint256 grnd, uint32 turnround, uint256 minimumshare , uint256 blockNumber , uint256 blockNumberTimeout, uint256 blockNumberCurrent , uint256 blockTimeAvg , uint32[8] highscores , address[8] addresses , bytes32[8] names , bytes32 myname) { uint32[8] memory highscoresm; address[8] memory addressesm; bytes32[8] memory namesm; for(uint i =0;i<8;i++) { highscoresm[i] = GameRoundData[ this_gRND].highscorePool[i]; uint32 id = GameRoundData[ this_gRND].highscorePool[8+i]; addressesm[i] = GameRoundData[ this_gRND ].IDtoAddress[ id ]; namesm[i] = view_get_registeredNames( addressesm[i ]); } return( this_gRND , GameRoundData[ this_gRND].extraData[0] , minimumSharePrice , GameRoundData[ this_gRND].blockNumber,GameRoundData[ this_gRND].blockNumberTimeout, block.number , blockTimeAverage , highscoresm , addressesm , namesm , view_get_registeredNames(msg.sender)); } function view_get_ResultData() public view returns(uint32 TotalPlayer, uint256 TotalPayout ,uint256 MyTokenValue, uint256 MyToken, uint256 MyGains , uint256 MyScore) { address _player_address = msg.sender; GameRoundData_s storage _GameRoundData = GameRoundData[ this_gRND ]; TotalPlayer = _GameRoundData.extraData[1]; TotalPayout = get_TotalPayout( _GameRoundData ); MyToken = PlayerGameRound[ _player_address][ this_gRND].token; MyTokenValue = MyToken * HDXcontract.sellingPrice( true ); MyTokenValue /= magnitude; MyGains = 0; if (PlayerData[ _player_address].gRND == this_gRND) { MyGains = get_PendingGainsAll( _player_address , this_gRND ); //just here for the view function so not used for any payout } MyScore = PlayerGameRound[_player_address][this_gRND].packedData[2]; } function totalEthereumBalance() public view returns(uint256) { return address(this).balance; } function view_get_maintenanceMode() public view returns(bool) { return( maintenanceMode); } function view_get_blockNumbers() public view returns( uint256 b1 , uint256 b2 ) { return( block.number , GameRoundData[ this_gRND ].blockNumberTimeout); } function view_get_registeredNames(address _player) public view returns( bytes32) { return( registeredNames[ _player ]); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); return c; } } library SafeMath128 { function mul(uint128 a, uint128 b) internal pure returns (uint128 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b); return c; } function sub(uint128 a, uint128 b) internal pure returns (uint128) { require(b <= a); return a - b; } function add(uint128 a, uint128 b) internal pure returns (uint128 c) { c = a + b; require(c >= a); return c; } }
seconds per block
uint256 private blockTimeAverage = 15;
1,760,993
[ 1, 7572, 1534, 1203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 1203, 950, 17115, 273, 4711, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x288A1Ebf7cC381228c01cE58D9cd6A20b70Db917/sources/New.sol
0.1% of the total supply
uint256 private constant AUTO_SELL_THRESHOLD = TOTAL_SUPPLY / 1000;
17,051,516
[ 1, 20, 18, 21, 9, 434, 326, 2078, 14467, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 5381, 17191, 67, 1090, 4503, 67, 23840, 273, 399, 19851, 67, 13272, 23893, 342, 4336, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "./IUniswapRouter.sol"; import "./IMasterchef.sol"; contract StrategyRamen is Ownable, Pausable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /** * @dev Tokens Used: * {wbnb} - Required for liquidity routing when doing swaps. * {ramen} - Token that the strategy maximizes. The same token that users deposit in the vault. */ address constant public wbnb = address(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); address constant public ramen = address(0x4F47A0d15c1E53F3d94c069C7D16977c29F9CB6B); /** * @dev Third Party Contracts: * {unirouter} - PancakeSwap unirouter * {masterchef} - MasterChef contract. */ address constant public unirouter = address(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); address constant public masterchef = address(0x97DD424B4628C8D3bD7fCf3A4e974Cebba011651); /** * @dev Ramen Contracts: * {vault} - Address of the vault that controls the strategy's funds. */ address constant public burnAddress = address(0x000000000000000000000000000000000000dEaD); address public vault; /** * @dev Distribution of fees earned. This allocations relative to the % implemented on chargeFees(). * Current implementation separates 10% for profit fees. * * {REWARDS_FEE} - 9.5% goes to Ramen BuyBack and Burn. * {CALL_FEE} - 0.5% goes to whoever executes the harvest function as gas subsidy. * {MAX_FEE} - Aux const used to safely calc the correct amounts. */ uint constant public REWARDS_FEE = 950; uint constant public CALL_FEE = 50; uint constant public MAX_FEE = 1000; /** * @dev Routes we take to swap tokens using PancakeSwap. * {ramenToWbnbRoute} - Route we take to go from {ramen} into {wbnb}. * {wbnbToRamenRoute} - Route we take to go from {wbnb} into {ramen}. */ address[] public ramenToWbnbRoute = [ramen, wbnb]; address[] public wbnbToRamenRoute = [wbnb, ramen]; /** * @dev Event that is fired each time someone harvests the strat. */ event StratHarvest(address indexed harvester); /** * @dev Initializes the strategy with the token that it will look to maximize. * @param _vault Address to initialize {vault} */ constructor(address _vault) public { vault = _vault; IERC20(ramen).safeApprove(masterchef, uint(-1)); IERC20(ramen).safeApprove(unirouter, uint(-1)); IERC20(wbnb).safeApprove(unirouter, uint(-1)); } /** * @dev Function that puts the funds to work. * It gets called whenever someone deposits in the strategy's vault contract. * It deposits ramen in the MasterChef to earn rewards in ramen. */ function deposit() public whenNotPaused { uint256 ramenBal = IERC20(ramen).balanceOf(address(this)); if (ramenBal > 0) { IMasterChef(masterchef).enterStaking(ramenBal); } } /** * @dev It withdraws ramen from the MasterChef and sends it to the vault. */ function withdraw(uint256 _amount) external { require(msg.sender == vault, "!vault"); uint256 ramenBal = IERC20(ramen).balanceOf(address(this)); if (ramenBal < _amount) { IMasterChef(masterchef).leaveStaking(_amount.sub(ramenBal)); ramenBal = IERC20(ramen).balanceOf(address(this)); } if (ramenBal > _amount) { ramenBal = _amount; } IERC20(ramen).safeTransfer(vault, ramenBal); } /** * @dev Core function of the strat, in charge of collecting and re-investing rewards. * 1. It claims rewards from the MasterChef * 2. It charges the system fee * 3. It re-invests the remaining profits. */ function harvest() external whenNotPaused { require(!Address.isContract(msg.sender), "!contract"); IMasterChef(masterchef).leaveStaking(0); chargeFees(); deposit(); emit StratHarvest(msg.sender); } /** * @dev Takes out 10% as system fees from the rewards. * 0.5% -> Call Fee * 9.5% -> BuyBack and Burn */ function chargeFees() internal { uint256 toWbnb = IERC20(ramen).balanceOf(address(this)).mul(10).div(100); IUniswapRouter(unirouter).swapExactTokensForTokens(toWbnb, 0, ramenToWbnbRoute, address(this), now.add(600)); uint256 wbnbBal = IERC20(wbnb).balanceOf(address(this)); uint256 callFee = wbnbBal.mul(CALL_FEE).div(MAX_FEE); IERC20(wbnb).safeTransfer(msg.sender, callFee); uint256 rewardsFee = wbnbBal.mul(REWARDS_FEE).div(MAX_FEE); IUniswapRouter(unirouter).swapExactTokensForTokens(rewardsFee, 0, wbnbToRamenRoute, burnAddress, now.add(600)); } /** * @dev Function to calculate the total underlaying {ramen} held by the strat. * It takes into account both the funds in hand, as the funds allocated in the MasterChef. */ function balanceOf() public view returns (uint256) { return balanceOfRamen().add(balanceOfPool()); } /** * @dev It calculates how much {ramen} the contract holds. */ function balanceOfRamen() public view returns (uint256) { return IERC20(ramen).balanceOf(address(this)); } /** * @dev It calculates how much {ramen} the strategy has allocated in the MasterChef */ function balanceOfPool() public view returns (uint256) { (uint256 _amount, ) = IMasterChef(masterchef).userInfo(0, address(this)); return _amount; } /** * @dev Function that has to be called as part of strat migration. It sends all the available funds back to the * vault, ready to be migrated to the new strat. */ function retireStrat() external { require(msg.sender == vault, "!vault"); IMasterChef(masterchef).emergencyWithdraw(0); uint256 ramenBal = IERC20(ramen).balanceOf(address(this)); IERC20(ramen).transfer(vault, ramenBal); } /** * @dev Pauses deposits. Withdraws all funds from the MasterChef, leaving rewards behind */ function panic() public onlyOwner { pause(); IMasterChef(masterchef).emergencyWithdraw(0); } /** * @dev Pauses the strat. */ function pause() public onlyOwner { _pause(); IERC20(ramen).safeApprove(masterchef, 0); IERC20(ramen).safeApprove(unirouter, 0); IERC20(wbnb).safeApprove(unirouter, 0); } /** * @dev Unpauses the strat. */ function unpause() external onlyOwner { _unpause(); IERC20(ramen).safeApprove(masterchef, uint(-1)); IERC20(ramen).safeApprove(unirouter, uint(-1)); IERC20(wbnb).safeApprove(unirouter, uint(-1)); } }
* @dev Pauses deposits. Withdraws all funds from the MasterChef, leaving rewards behind/
function panic() public onlyOwner { pause(); IMasterChef(masterchef).emergencyWithdraw(0); }
2,526,051
[ 1, 52, 9608, 443, 917, 1282, 18, 3423, 9446, 87, 777, 284, 19156, 628, 326, 13453, 39, 580, 74, 16, 15086, 283, 6397, 21478, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3933, 1435, 1071, 1338, 5541, 288, 203, 3639, 11722, 5621, 203, 3639, 6246, 2440, 39, 580, 74, 12, 7525, 343, 10241, 2934, 351, 24530, 1190, 9446, 12, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
import 'actor/base_actor.sol'; import 'dapple/test.sol'; import 'dapple/debug.sol'; // Simple example and passthrough for testing contract DSSimpleActor is DSBaseActor { function execute( address target, bytes calldata, uint value ) { exec( target, calldata, value ); } function tryExecute( address target, bytes calldata, uint value ) returns (bool call_ret ) { return tryExec( target, calldata, value ); } } // Test helper: record calldata from fallback and compare. contract CallReceiver is Debug { bytes last_calldata; uint last_value; function compareLastCalldata( bytes data ) returns (bool) { // last_calldata.length might be longer because calldata is padded // to be a multiple of the word size if( data.length > last_calldata.length ) { return false; } for( var i = 0; i < data.length; i++ ) { if( data[i] != last_calldata[i] ) { return false; } } return true; } function() { last_calldata = msg.data; last_value = msg.value; } } // actually tests "SimpleActorTest" contract DSBaseActorTest is Test { bytes calldata; DSSimpleActor a; CallReceiver cr; function setUp() { assertTrue(this.balance > 0, "insufficient funds"); a = new DSSimpleActor(); a.send(10 wei); cr = new CallReceiver(); } function testProxyCall() { for( var i = 0; i < 35; i++ ) { calldata.push(byte(i)); } a.execute( address(cr), calldata, 0 ); assertTrue( cr.compareLastCalldata( calldata ) ); } function testTryProxyCall() { for( var i = 0; i < 35; i++ ) { calldata.push(byte(i)); } assertTrue(a.tryExecute( address(cr), calldata, 0 )); assertTrue( cr.compareLastCalldata( calldata ) ); } function testProxyCallWithValue() { assertEq(cr.balance, 0, "callreceiver already has ether"); for( var i = 0; i < 35; i++ ) { calldata.push(byte(i)); } assertEq(a.balance, 10 wei, "ether not sent to actor"); a.execute(address(cr), calldata, 10 wei); assertTrue( cr.compareLastCalldata( calldata ), "call data does not match" ); assertEq(cr.balance, 10 wei); } function testTryProxyCallWithValue() { assertEq(cr.balance, 0, "callreceiver already has ether"); for( var i = 0; i < 35; i++ ) { calldata.push(byte(i)); } assertEq(a.balance, 10 wei, "ether not sent to actor"); assertTrue(a.tryExecute(address(cr), calldata, 10 wei), "tryExecute failed"); assertTrue( cr.compareLastCalldata( calldata ), "call data does not match" ); assertEq(cr.balance, 10 wei); } }
actually tests "SimpleActorTest"
contract DSBaseActorTest is Test { bytes calldata; DSSimpleActor a; CallReceiver cr; function setUp() { assertTrue(this.balance > 0, "insufficient funds"); a = new DSSimpleActor(); a.send(10 wei); cr = new CallReceiver(); } function testProxyCall() { for( var i = 0; i < 35; i++ ) { calldata.push(byte(i)); } a.execute( address(cr), calldata, 0 ); assertTrue( cr.compareLastCalldata( calldata ) ); } function testProxyCall() { for( var i = 0; i < 35; i++ ) { calldata.push(byte(i)); } a.execute( address(cr), calldata, 0 ); assertTrue( cr.compareLastCalldata( calldata ) ); } function testTryProxyCall() { for( var i = 0; i < 35; i++ ) { calldata.push(byte(i)); } assertTrue(a.tryExecute( address(cr), calldata, 0 )); assertTrue( cr.compareLastCalldata( calldata ) ); } function testTryProxyCall() { for( var i = 0; i < 35; i++ ) { calldata.push(byte(i)); } assertTrue(a.tryExecute( address(cr), calldata, 0 )); assertTrue( cr.compareLastCalldata( calldata ) ); } function testProxyCallWithValue() { assertEq(cr.balance, 0, "callreceiver already has ether"); for( var i = 0; i < 35; i++ ) { calldata.push(byte(i)); } assertEq(a.balance, 10 wei, "ether not sent to actor"); a.execute(address(cr), calldata, 10 wei); assertTrue( cr.compareLastCalldata( calldata ), "call data does not match" ); assertEq(cr.balance, 10 wei); } function testProxyCallWithValue() { assertEq(cr.balance, 0, "callreceiver already has ether"); for( var i = 0; i < 35; i++ ) { calldata.push(byte(i)); } assertEq(a.balance, 10 wei, "ether not sent to actor"); a.execute(address(cr), calldata, 10 wei); assertTrue( cr.compareLastCalldata( calldata ), "call data does not match" ); assertEq(cr.balance, 10 wei); } function testTryProxyCallWithValue() { assertEq(cr.balance, 0, "callreceiver already has ether"); for( var i = 0; i < 35; i++ ) { calldata.push(byte(i)); } assertEq(a.balance, 10 wei, "ether not sent to actor"); assertTrue(a.tryExecute(address(cr), calldata, 10 wei), "tryExecute failed"); assertTrue( cr.compareLastCalldata( calldata ), "call data does not match" ); assertEq(cr.balance, 10 wei); } function testTryProxyCallWithValue() { assertEq(cr.balance, 0, "callreceiver already has ether"); for( var i = 0; i < 35; i++ ) { calldata.push(byte(i)); } assertEq(a.balance, 10 wei, "ether not sent to actor"); assertTrue(a.tryExecute(address(cr), calldata, 10 wei), "tryExecute failed"); assertTrue( cr.compareLastCalldata( calldata ), "call data does not match" ); assertEq(cr.balance, 10 wei); } }
914,116
[ 1, 621, 3452, 7434, 315, 5784, 17876, 4709, 6, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 8678, 2171, 17876, 4709, 353, 7766, 288, 203, 565, 1731, 745, 892, 31, 203, 565, 463, 1260, 2052, 17876, 279, 31, 203, 565, 3049, 12952, 4422, 31, 203, 565, 445, 24292, 1435, 288, 203, 3639, 1815, 5510, 12, 2211, 18, 12296, 405, 374, 16, 315, 2679, 11339, 284, 19156, 8863, 203, 203, 3639, 279, 273, 394, 463, 1260, 2052, 17876, 5621, 203, 3639, 279, 18, 4661, 12, 2163, 732, 77, 1769, 203, 3639, 4422, 273, 394, 3049, 12952, 5621, 203, 565, 289, 203, 565, 445, 1842, 3886, 1477, 1435, 288, 203, 3639, 364, 12, 569, 277, 273, 374, 31, 277, 411, 13191, 31, 277, 9904, 262, 288, 203, 5411, 745, 892, 18, 6206, 12, 7229, 12, 77, 10019, 203, 3639, 289, 203, 3639, 279, 18, 8837, 12, 1758, 12, 3353, 3631, 745, 892, 16, 374, 11272, 203, 3639, 1815, 5510, 12, 4422, 18, 9877, 3024, 1477, 892, 12, 745, 892, 262, 11272, 203, 565, 289, 203, 565, 445, 1842, 3886, 1477, 1435, 288, 203, 3639, 364, 12, 569, 277, 273, 374, 31, 277, 411, 13191, 31, 277, 9904, 262, 288, 203, 5411, 745, 892, 18, 6206, 12, 7229, 12, 77, 10019, 203, 3639, 289, 203, 3639, 279, 18, 8837, 12, 1758, 12, 3353, 3631, 745, 892, 16, 374, 11272, 203, 3639, 1815, 5510, 12, 4422, 18, 9877, 3024, 1477, 892, 12, 745, 892, 262, 11272, 203, 565, 289, 203, 565, 445, 1842, 7833, 3886, 1477, 1435, 288, 203, 3639, 364, 12, 569, 277, 273, 374, 31, 277, 411, 13191, 31, 277, 9904, 262, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUtil { /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } interface IStakingProxy { function getBalance() external view returns(uint256); function withdraw(uint256 _amount) external; function stake() external; function distribute() external; } interface IRewardStaking { function stakeFor(address, uint256) external; function stake( uint256) external; function withdraw(uint256 amount, bool claim) external; function withdrawAndUnwrap(uint256 amount, bool claim) external; function earned(address account) external view returns (uint256); function getReward() external; function getReward(address _account, bool _claimExtras) external; function extraRewardsLength() external view returns (uint256); function extraRewards(uint256 _pid) external view returns (address); function rewardToken() external view returns (address); function balanceOf(address _account) external view returns (uint256); } /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "BoringMath: division by zero"); return a / b; } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } function to40(uint256 a) internal pure returns (uint40 c) { require(a <= uint40(-1), "BoringMath: uint40 Overflow"); c = uint40(a); } function to112(uint256 a) internal pure returns (uint112 c) { require(a <= uint112(-1), "BoringMath: uint112 Overflow"); c = uint112(a); } function to224(uint256 a) internal pure returns (uint224 c) { require(a <= uint224(-1), "BoringMath: uint224 Overflow"); c = uint224(a); } function to208(uint256 a) internal pure returns (uint208 c) { require(a <= uint208(-1), "BoringMath: uint208 Overflow"); c = uint208(a); } function to216(uint256 a) internal pure returns (uint216 c) { require(a <= uint216(-1), "BoringMath: uint216 Overflow"); c = uint216(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint32 a, uint32 b) internal pure returns (uint32 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint32 a, uint32 b) internal pure returns (uint32) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint112. library BoringMath112 { function add(uint112 a, uint112 b) internal pure returns (uint112 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint112 a, uint112 b) internal pure returns (uint112 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint112 a, uint112 b) internal pure returns (uint112 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint112 a, uint112 b) internal pure returns (uint112) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint224. library BoringMath224 { function add(uint224 a, uint224 b) internal pure returns (uint224 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint224 a, uint224 b) internal pure returns (uint224 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint224 a, uint224 b) internal pure returns (uint224 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint224 a, uint224 b) internal pure returns (uint224) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { 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 Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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 SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @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); } } // solhint-disable-next-line compiler-version /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } /* * @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 ContextUpgradeable is Initializable { 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. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } /** * @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 ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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; } uint256[49] private __gap; } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } interface IGac { function paused() external view returns (bool); function transferFromDisabled() external view returns (bool); function unpause() external; function pause() external; function enableTransferFrom() external; function disableTransferFrom() external; function grantRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function getRoleMember(bytes32 role, uint256 index) external view returns (address); } /** * @title Global Access Control Managed - Base Class * @notice allows inheriting contracts to leverage global access control permissions conveniently, as well as granting contract-specific pausing functionality */ contract GlobalAccessControlManaged is PausableUpgradeable { IGac public gac; bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant UNPAUSER_ROLE = keccak256("UNPAUSER_ROLE"); /// ======================= /// ===== Initializer ===== /// ======================= /** * @notice Initializer * @dev this is assumed to be used in the initializer of the inhereiting contract * @param _globalAccessControl global access control which is pinged to allow / deny access to permissioned calls by role */ function __GlobalAccessControlManaged_init(address _globalAccessControl) public initializer { __Pausable_init_unchained(); gac = IGac(_globalAccessControl); } /// ===================== /// ===== Modifiers ===== /// ===================== // @dev only holders of the given role on the GAC can call modifier onlyRole(bytes32 role) { require(gac.hasRole(role, msg.sender), "GAC: invalid-caller-role"); _; } // @dev only holders of any of the given set of roles on the GAC can call modifier onlyRoles(bytes32[] memory roles) { bool validRoleFound = false; for (uint256 i = 0; i < roles.length; i++) { bytes32 role = roles[i]; if (gac.hasRole(role, msg.sender)) { validRoleFound = true; break; } } require(validRoleFound, "GAC: invalid-caller-role"); _; } // @dev only holders of the given role on the GAC can call, or a specified address // @dev used to faciliate extra contract-specific permissioned accounts modifier onlyRoleOrAddress(bytes32 role, address account) { require( gac.hasRole(role, msg.sender) || msg.sender == account, "GAC: invalid-caller-role-or-address" ); _; } /// @dev can be pausable by GAC or local flag modifier gacPausable() { require(!gac.paused(), "global-paused"); require(!paused(), "local-paused"); _; } /// ================================ /// ===== Permissioned actions ===== /// ================================ function pause() external { require(gac.hasRole(PAUSER_ROLE, msg.sender)); _pause(); } function unpause() external { require(gac.hasRole(UNPAUSER_ROLE, msg.sender)); _unpause(); } } /* Citadel locking contract Adapted from CvxLockerV2.sol (https://github.com/convex-eth/platform/blob/4a51cf7e411db27fa8fc2244137013f9fbdebb38/contracts/contracts/CvxLockerV2.sol). Changes: - Upgradeability - Removed staking */ contract StakedCitadelLocker is Initializable, ReentrancyGuardUpgradeable, OwnableUpgradeable, GlobalAccessControlManaged { using BoringMath for uint256; using BoringMath224 for uint224; using BoringMath112 for uint112; using BoringMath32 for uint32; using SafeERC20Upgradeable for IERC20Upgradeable; /* ========== STATE VARIABLES ========== */ struct Reward { bool useBoost; uint40 periodFinish; uint208 rewardRate; uint40 lastUpdateTime; uint208 rewardPerTokenStored; } struct Balances { uint112 locked; uint112 boosted; uint32 nextUnlockIndex; } struct LockedBalance { uint112 amount; uint112 boosted; uint32 unlockTime; } struct EarnedData { address token; uint256 amount; } struct Epoch { uint224 supply; //epoch boosted supply uint32 date; //epoch start date } //token constants IERC20Upgradeable public stakingToken; // xCTDL token //rewards address[] public rewardTokens; mapping(address => Reward) public rewardData; // Duration that rewards are streamed over uint256 public constant rewardsDuration = 86400; // 1 day // Duration of lock/earned penalty period uint256 public constant lockDuration = rewardsDuration * 7 * 21; // 21 weeks // reward token -> distributor -> is approved to add rewards mapping(address => mapping(address => bool)) public rewardDistributors; // user -> reward token -> amount mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid; mapping(address => mapping(address => uint256)) public rewards; //supplies and epochs uint256 public lockedSupply; uint256 public boostedSupply; Epoch[] public epochs; //mappings for balance data mapping(address => Balances) public balances; mapping(address => LockedBalance[]) public userLocks; // ========== Not used ========== //boost address public boostPayment = address(0); uint256 public maximumBoostPayment = 0; uint256 public boostRate = 10000; uint256 public nextMaximumBoostPayment = 0; uint256 public nextBoostRate = 10000; uint256 public constant denominator = 10000; // ============================== //staking uint256 public minimumStake = 10000; uint256 public maximumStake = 10000; address public stakingProxy = address(0); uint256 public constant stakeOffsetOnLock = 500; //allow broader range for staking when depositing //management uint256 public kickRewardPerEpoch = 100; uint256 public kickRewardEpochDelay = 4; //shutdown bool public isShutdown = false; //erc20-like interface string private _name; string private _symbol; uint8 private _decimals; /* ========== CONSTRUCTOR ========== */ function initialize( address _stakingToken, address _gac, string calldata name, string calldata symbol ) public initializer { require(_stakingToken != address(0)); // dev: _stakingToken address should not be zero stakingToken = IERC20Upgradeable(_stakingToken); _name = name; _symbol = symbol; _decimals = 18; uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)})); __Ownable_init(); __ReentrancyGuard_init(); __GlobalAccessControlManaged_init(_gac); } function decimals() public view returns (uint8) { return _decimals; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function version() public view returns (uint256) { return 2; } /* ========== ADMIN CONFIGURATION ========== */ // Add a new reward token to be distributed to stakers function addReward( address _rewardsToken, address _distributor, bool _useBoost ) public onlyOwner gacPausable { require(rewardData[_rewardsToken].lastUpdateTime == 0); // require(_rewardsToken != address(stakingToken)); rewardTokens.push(_rewardsToken); rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp); rewardData[_rewardsToken].periodFinish = uint40(block.timestamp); rewardData[_rewardsToken].useBoost = _useBoost; rewardDistributors[_rewardsToken][_distributor] = true; } // Modify approval for an address to call notifyRewardAmount function approveRewardDistributor( address _rewardsToken, address _distributor, bool _approved ) external onlyOwner gacPausable { require(rewardData[_rewardsToken].lastUpdateTime > 0); rewardDistributors[_rewardsToken][_distributor] = _approved; } //Set the staking contract for the underlying cvx function setStakingContract(address _staking) external onlyOwner gacPausable { require(stakingProxy == address(0), "!assign"); stakingProxy = _staking; } //set staking limits. will stake the mean of the two once either ratio is crossed function setStakeLimits(uint256 _minimum, uint256 _maximum) external onlyOwner gacPausable { require(_minimum <= denominator, "min range"); require(_maximum <= denominator, "max range"); require(_minimum <= _maximum, "min range"); minimumStake = _minimum; maximumStake = _maximum; updateStakeRatio(0); } //set boost parameters function setBoost( uint256 _max, uint256 _rate, address _receivingAddress ) external onlyOwner gacPausable { require(_max < 1500, "over max payment"); //max 15% require(_rate < 30000, "over max rate"); //max 3x require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid nextMaximumBoostPayment = _max; nextBoostRate = _rate; boostPayment = _receivingAddress; } //set kick incentive function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner gacPausable { require(_rate <= 500, "over max rate"); //max 5% per epoch require(_delay >= 2, "min delay"); //minimum 2 epochs of grace kickRewardPerEpoch = _rate; kickRewardEpochDelay = _delay; } //shutdown the contract. unstake all tokens. release all locks function shutdown() external onlyOwner { isShutdown = true; } /* ========== VIEWS ========== */ function getRewardTokens() external view returns (address[] memory) { uint256 numTokens = rewardTokens.length; address[] memory tokens = new address[](numTokens); for (uint256 i = 0; i < numTokens; i++) { tokens[i] = rewardTokens[i]; } return tokens; } function _rewardPerToken(address _rewardsToken) internal view returns (uint256) { if (boostedSupply == 0) { return rewardData[_rewardsToken].rewardPerTokenStored; } return uint256(rewardData[_rewardsToken].rewardPerTokenStored).add( _lastTimeRewardApplicable( rewardData[_rewardsToken].periodFinish ) .sub(rewardData[_rewardsToken].lastUpdateTime) .mul(rewardData[_rewardsToken].rewardRate) .mul(1e18) .div( rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply ) ); } function _earned( address _user, address _rewardsToken, uint256 _balance ) internal view returns (uint256) { return _balance .mul( _rewardPerToken(_rewardsToken).sub( userRewardPerTokenPaid[_user][_rewardsToken] ) ) .div(1e18) .add(rewards[_user][_rewardsToken]); } function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) { return MathUpgradeable.min(block.timestamp, _finishTime); } function lastTimeRewardApplicable(address _rewardsToken) public view returns (uint256) { return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish); } function rewardPerToken(address _rewardsToken) external view returns (uint256) { return _rewardPerToken(_rewardsToken); } function getRewardForDuration(address _rewardsToken) external view returns (uint256) { return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration); } // Address and claimable amount of all reward tokens for the given account function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) { userRewards = new EarnedData[](rewardTokens.length); Balances storage userBalance = balances[_account]; uint256 boostedBal = userBalance.boosted; for (uint256 i = 0; i < userRewards.length; i++) { address token = rewardTokens[i]; userRewards[i].token = token; userRewards[i].amount = _earned( _account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked ); } return userRewards; } // Total BOOSTED balance of an account, including unlocked but not withdrawn tokens function rewardWeightOf(address _user) external view returns (uint256 amount) { return balances[_user].boosted; } // total token balance of an account, including unlocked but not withdrawn tokens function lockedBalanceOf(address _user) external view returns (uint256 amount) { return balances[_user].locked; } //BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch function balanceOf(address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; Balances storage userBalance = balances[_user]; uint256 nextUnlockIndex = userBalance.nextUnlockIndex; //start with current boosted amount amount = balances[_user].boosted; uint256 locksLength = locks.length; //remove old records only (will be better gas-wise than adding up) for (uint256 i = nextUnlockIndex; i < locksLength; i++) { if (locks[i].unlockTime <= block.timestamp) { amount = amount.sub(locks[i].boosted); } else { //stop now as no futher checks are needed break; } } //also remove amount locked in the next epoch uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); if ( locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) > currentEpoch ) { amount = amount.sub(locks[locksLength - 1].boosted); } return amount; } //BOOSTED balance of an account which only includes properly locked tokens at the given epoch function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; //get timestamp of given epoch index uint256 epochTime = epochs[_epoch].date; //get timestamp of first non-inclusive epoch uint256 cutoffEpoch = epochTime.sub(lockDuration); //need to add up since the range could be in the middle somewhere //traverse inversely to make more current queries more gas efficient for (uint256 i = locks.length - 1; i + 1 != 0; i--) { uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration); //lock epoch must be less or equal to the epoch we're basing from. if (lockEpoch <= epochTime) { if (lockEpoch > cutoffEpoch) { amount = amount.add(locks[i].boosted); } else { //stop now as no futher checks matter break; } } } return amount; } //return currently locked but not active balance function pendingLockOf(address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; uint256 locksLength = locks.length; //return amount if latest lock is in the future uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); if ( locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) > currentEpoch ) { return locks[locksLength - 1].boosted; } return 0; } function pendingLockAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[_user]; //get next epoch from the given epoch index uint256 nextEpoch = uint256(epochs[_epoch].date).add(rewardsDuration); //traverse inversely to make more current queries more gas efficient for (uint256 i = locks.length - 1; i + 1 != 0; i--) { uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration); //return the next epoch balance if (lockEpoch == nextEpoch) { return locks[i].boosted; } else if (lockEpoch < nextEpoch) { //no need to check anymore break; } } return 0; } //supply of all properly locked BOOSTED balances at most recent eligible epoch function totalSupply() external view returns (uint256 supply) { uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); uint256 cutoffEpoch = currentEpoch.sub(lockDuration); uint256 epochindex = epochs.length; //do not include next epoch's supply if (uint256(epochs[epochindex - 1].date) > currentEpoch) { epochindex--; } //traverse inversely to make more current queries more gas efficient for (uint256 i = epochindex - 1; i + 1 != 0; i--) { Epoch storage e = epochs[i]; if (uint256(e.date) <= cutoffEpoch) { break; } supply = supply.add(e.supply); } return supply; } //supply of all properly locked BOOSTED balances at the given epoch function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply) { uint256 epochStart = uint256(epochs[_epoch].date) .div(rewardsDuration) .mul(rewardsDuration); uint256 cutoffEpoch = epochStart.sub(lockDuration); //traverse inversely to make more current queries more gas efficient for (uint256 i = _epoch; i + 1 != 0; i--) { Epoch storage e = epochs[i]; if (uint256(e.date) <= cutoffEpoch) { break; } supply = supply.add(epochs[i].supply); } return supply; } //find an epoch index based on timestamp function findEpochId(uint256 _time) external view returns (uint256 epoch) { uint256 max = epochs.length - 1; uint256 min = 0; //convert to start point _time = _time.div(rewardsDuration).mul(rewardsDuration); for (uint256 i = 0; i < 128; i++) { if (min >= max) break; uint256 mid = (min + max + 1) / 2; uint256 midEpochBlock = epochs[mid].date; if (midEpochBlock == _time) { //found return mid; } else if (midEpochBlock < _time) { min = mid; } else { max = mid - 1; } } return min; } // Information on a user's locked balances function lockedBalances(address _user) external view returns ( uint256 total, uint256 unlockable, uint256 locked, LockedBalance[] memory lockData ) { LockedBalance[] storage locks = userLocks[_user]; Balances storage userBalance = balances[_user]; uint256 nextUnlockIndex = userBalance.nextUnlockIndex; uint256 idx; for (uint256 i = nextUnlockIndex; i < locks.length; i++) { if (locks[i].unlockTime > block.timestamp) { if (idx == 0) { lockData = new LockedBalance[](locks.length - i); } lockData[idx] = locks[i]; idx++; locked = locked.add(locks[i].amount); } else { unlockable = unlockable.add(locks[i].amount); } } return (userBalance.locked, unlockable, locked, lockData); } //number of epochs function epochCount() external view returns (uint256) { return epochs.length; } /* ========== MUTATIVE FUNCTIONS ========== */ function checkpointEpoch() external { _checkpointEpoch(); } //insert a new epoch if needed. fill in any gaps function _checkpointEpoch() internal { //create new epoch in the future where new non-active locks will lock to uint256 nextEpoch = block .timestamp .div(rewardsDuration) .mul(rewardsDuration) .add(rewardsDuration); uint256 epochindex = epochs.length; //first epoch add in constructor, no need to check 0 length //check to add if (epochs[epochindex - 1].date < nextEpoch) { //fill any epoch gaps while (epochs[epochs.length - 1].date != nextEpoch) { uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date) .add(rewardsDuration); epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)})); } //update boost parameters on a new epoch if (boostRate != nextBoostRate) { boostRate = nextBoostRate; } if (maximumBoostPayment != nextMaximumBoostPayment) { maximumBoostPayment = nextMaximumBoostPayment; } } } // Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards function lock( address _account, uint256 _amount, uint256 _spendRatio ) external nonReentrant gacPausable updateReward(_account) { //pull tokens stakingToken.safeTransferFrom(msg.sender, address(this), _amount); //lock _lock(_account, _amount, _spendRatio, false); } //lock tokens function _lock( address _account, uint256 _amount, uint256 _spendRatio, bool _isRelock ) internal { require(_amount > 0, "Cannot stake 0"); require(_spendRatio <= maximumBoostPayment, "over max spend"); require(!isShutdown, "shutdown"); Balances storage bal = balances[_account]; //must try check pointing epoch first _checkpointEpoch(); //calc lock and boosted amount uint256 spendAmount = _amount.mul(_spendRatio).div(denominator); uint256 boostRatio = boostRate.mul(_spendRatio).div( maximumBoostPayment == 0 ? 1 : maximumBoostPayment ); uint112 lockAmount = _amount.sub(spendAmount).to112(); uint112 boostedAmount = _amount .add(_amount.mul(boostRatio).div(denominator)) .to112(); //add user balances bal.locked = bal.locked.add(lockAmount); bal.boosted = bal.boosted.add(boostedAmount); //add to total supplies lockedSupply = lockedSupply.add(lockAmount); boostedSupply = boostedSupply.add(boostedAmount); //add user lock records or add to current uint256 lockEpoch = block.timestamp.div(rewardsDuration).mul( rewardsDuration ); //if a fresh lock, add on an extra duration period if (!_isRelock) { lockEpoch = lockEpoch.add(rewardsDuration); } uint256 unlockTime = lockEpoch.add(lockDuration); uint256 idx = userLocks[_account].length; //if the latest user lock is smaller than this lock, always just add new entry to the end of the list if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) { userLocks[_account].push( LockedBalance({ amount: lockAmount, boosted: boostedAmount, unlockTime: uint32(unlockTime) }) ); } else { //else add to a current lock //if latest lock is further in the future, lower index //this can only happen if relocking an expired lock after creating a new lock if (userLocks[_account][idx - 1].unlockTime > unlockTime) { idx--; } //if idx points to the epoch when same unlock time, update //(this is always true with a normal lock but maybe not with relock) if (userLocks[_account][idx - 1].unlockTime == unlockTime) { LockedBalance storage userL = userLocks[_account][idx - 1]; userL.amount = userL.amount.add(lockAmount); userL.boosted = userL.boosted.add(boostedAmount); } else { //can only enter here if a relock is made after a lock and there's no lock entry //for the current epoch. //ex a list of locks such as "[...][older][current*][next]" but without a "current" lock //length - 1 is the next epoch //length - 2 is a past epoch //thus need to insert an entry for current epoch at the 2nd to last entry //we will copy and insert the tail entry(next) and then overwrite length-2 entry //reset idx idx = userLocks[_account].length; //get current last item LockedBalance storage userL = userLocks[_account][idx - 1]; //add a copy to end of list userLocks[_account].push( LockedBalance({ amount: userL.amount, boosted: userL.boosted, unlockTime: userL.unlockTime }) ); //insert current epoch lock entry by overwriting the entry at length-2 userL.amount = lockAmount; userL.boosted = boostedAmount; userL.unlockTime = uint32(unlockTime); } } //update epoch supply, epoch checkpointed above so safe to add to latest uint256 eIndex = epochs.length - 1; //if relock, epoch should be current and not next, thus need to decrease index to length-2 if (_isRelock) { eIndex--; } Epoch storage e = epochs[eIndex]; e.supply = e.supply.add(uint224(boostedAmount)); //send boost payment if (spendAmount > 0) { stakingToken.safeTransfer(boostPayment, spendAmount); } emit Staked(_account, lockEpoch, _amount, lockAmount, boostedAmount); } // Withdraw all currently locked tokens where the unlock time has passed function _processExpiredLocks( address _account, bool _relock, uint256 _spendRatio, address _withdrawTo, address _rewardAddress, uint256 _checkDelay ) internal updateReward(_account) { LockedBalance[] storage locks = userLocks[_account]; Balances storage userBalance = balances[_account]; uint112 locked; uint112 boostedAmount; uint256 length = locks.length; uint256 reward = 0; if ( isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay) ) { //if time is beyond last lock, can just bundle everything together locked = userBalance.locked; boostedAmount = userBalance.boosted; //dont delete, just set next index userBalance.nextUnlockIndex = length.to32(); //check for kick reward //this wont have the exact reward rate that you would get if looped through //but this section is supposed to be for quick and easy low gas processing of all locks //we'll assume that if the reward was good enough someone would have processed at an earlier epoch if (_checkDelay > 0) { uint256 currentEpoch = block .timestamp .sub(_checkDelay) .div(rewardsDuration) .mul(rewardsDuration); uint256 epochsover = currentEpoch .sub(uint256(locks[length - 1].unlockTime)) .div(rewardsDuration); uint256 rRate = MathUtil.min( kickRewardPerEpoch.mul(epochsover + 1), denominator ); reward = uint256(locks[length - 1].amount).mul(rRate).div( denominator ); } } else { //use a processed index(nextUnlockIndex) to not loop as much //deleting does not change array length uint32 nextUnlockIndex = userBalance.nextUnlockIndex; for (uint256 i = nextUnlockIndex; i < length; i++) { //unlock time must be less or equal to time if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break; //add to cumulative amounts locked = locked.add(locks[i].amount); boostedAmount = boostedAmount.add(locks[i].boosted); //check for kick reward //each epoch over due increases reward if (_checkDelay > 0) { uint256 currentEpoch = block .timestamp .sub(_checkDelay) .div(rewardsDuration) .mul(rewardsDuration); uint256 epochsover = currentEpoch .sub(uint256(locks[i].unlockTime)) .div(rewardsDuration); uint256 rRate = MathUtil.min( kickRewardPerEpoch.mul(epochsover + 1), denominator ); reward = reward.add( uint256(locks[i].amount).mul(rRate).div(denominator) ); } //set next unlock index nextUnlockIndex++; } //update next unlock index userBalance.nextUnlockIndex = nextUnlockIndex; } require(locked > 0, "no exp locks"); //update user balances and total supplies userBalance.locked = userBalance.locked.sub(locked); userBalance.boosted = userBalance.boosted.sub(boostedAmount); lockedSupply = lockedSupply.sub(locked); boostedSupply = boostedSupply.sub(boostedAmount); emit Withdrawn(_account, locked, _relock); //send process incentive if (reward > 0) { //if theres a reward(kicked), it will always be a withdraw only //preallocate enough cvx from stake contract to pay for both reward and withdraw allocateCVXForTransfer(uint256(locked)); //reduce return amount by the kick reward locked = locked.sub(reward.to112()); //transfer reward transferCVX(_rewardAddress, reward, false); emit KickReward(_rewardAddress, _account, reward); } else if (_spendRatio > 0) { //preallocate enough cvx to transfer the boost cost allocateCVXForTransfer( uint256(locked).mul(_spendRatio).div(denominator) ); } //relock or return to user if (_relock) { _lock(_withdrawTo, locked, _spendRatio, true); } else { transferCVX(_withdrawTo, locked, true); } } // withdraw expired locks to a different address function withdrawExpiredLocksTo(address _withdrawTo) external nonReentrant gacPausable { _processExpiredLocks(msg.sender, false, 0, _withdrawTo, msg.sender, 0); } // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks(bool _relock) external nonReentrant gacPausable { _processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0); } function kickExpiredLocks(address _account) external nonReentrant gacPausable { //allow kick after grace period of 'kickRewardEpochDelay' _processExpiredLocks( _account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay) ); } //pull required amount of cvx from staking for an upcoming transfer // dev: no-op function allocateCVXForTransfer(uint256 _amount) internal { uint256 balance = stakingToken.balanceOf(address(this)); } //transfer helper: pull enough from staking, transfer, updating staking ratio function transferCVX( address _account, uint256 _amount, bool _updateStake ) internal { //allocate enough cvx from staking for the transfer allocateCVXForTransfer(_amount); //transfer stakingToken.safeTransfer(_account, _amount); } //calculate how much cvx should be staked. update if needed function updateStakeRatio(uint256 _offset) internal { if (isShutdown) return; //get balances uint256 local = stakingToken.balanceOf(address(this)); uint256 staked = IStakingProxy(stakingProxy).getBalance(); uint256 total = local.add(staked); if (total == 0) return; //current staked ratio uint256 ratio = staked.mul(denominator).div(total); //mean will be where we reset to if unbalanced uint256 mean = maximumStake.add(minimumStake).div(2); uint256 max = maximumStake.add(_offset); uint256 min = MathUpgradeable.min(minimumStake, minimumStake - _offset); if (ratio > max) { //remove uint256 remove = staked.sub(total.mul(mean).div(denominator)); IStakingProxy(stakingProxy).withdraw(remove); } else if (ratio < min) { //add uint256 increase = total.mul(mean).div(denominator).sub(staked); stakingToken.safeTransfer(stakingProxy, increase); IStakingProxy(stakingProxy).stake(); } } // Claim all pending rewards function getReward(address _account, bool _stake) public nonReentrant gacPausable updateReward(_account) { for (uint256 i; i < rewardTokens.length; i++) { address _rewardsToken = rewardTokens[i]; uint256 reward = rewards[_account][_rewardsToken]; if (reward > 0) { rewards[_account][_rewardsToken] = 0; IERC20Upgradeable(_rewardsToken).safeTransfer(_account, reward); emit RewardPaid(_account, _rewardsToken, reward); } } } // claim all pending rewards function getReward(address _account) external { getReward(_account, false); } /* ========== RESTRICTED FUNCTIONS ========== */ function _notifyReward(address _rewardsToken, uint256 _reward) internal { Reward storage rdata = rewardData[_rewardsToken]; if (block.timestamp >= rdata.periodFinish) { rdata.rewardRate = _reward.div(rewardsDuration).to208(); } else { uint256 remaining = uint256(rdata.periodFinish).sub( block.timestamp ); uint256 leftover = remaining.mul(rdata.rewardRate); rdata.rewardRate = _reward .add(leftover) .div(rewardsDuration) .to208(); } rdata.lastUpdateTime = block.timestamp.to40(); rdata.periodFinish = block.timestamp.add(rewardsDuration).to40(); } function notifyRewardAmount(address _rewardsToken, uint256 _reward) external gacPausable updateReward(address(0)) { require(rewardDistributors[_rewardsToken][msg.sender]); require(_reward > 0, "No reward"); _notifyReward(_rewardsToken, _reward); // handle the transfer of reward tokens via `transferFrom` to reduce the number // of transactions required and ensure correctness of the _reward amount IERC20Upgradeable(_rewardsToken).safeTransferFrom( msg.sender, address(this), _reward ); emit RewardAdded(_rewardsToken, _reward); } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner gacPausable { require( _tokenAddress != address(stakingToken), "Cannot withdraw staking token" ); require( rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token" ); IERC20Upgradeable(_tokenAddress).safeTransfer(owner(), _tokenAmount); emit Recovered(_tokenAddress, _tokenAmount); } /* ========== MODIFIERS ========== */ modifier updateReward(address _account) { { //stack too deep Balances storage userBalance = balances[_account]; uint256 boostedBal = userBalance.boosted; for (uint256 i = 0; i < rewardTokens.length; i++) { address token = rewardTokens[i]; rewardData[token].rewardPerTokenStored = _rewardPerToken(token) .to208(); rewardData[token].lastUpdateTime = _lastTimeRewardApplicable( rewardData[token].periodFinish ).to40(); if (_account != address(0)) { //check if reward is boostable or not. use boosted or locked balance accordingly rewards[_account][token] = _earned( _account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked ); userRewardPerTokenPaid[_account][token] = rewardData[token] .rewardPerTokenStored; } } } _; } /* ========== EVENTS ========== */ event RewardAdded(address indexed _token, uint256 _reward); event Staked( address indexed _user, uint256 indexed _epoch, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount ); event Withdrawn(address indexed _user, uint256 _amount, bool _relocked); event KickReward( address indexed _user, address indexed _kicked, uint256 _reward ); event RewardPaid( address indexed _user, address indexed _rewardsToken, uint256 _reward ); event Recovered(address _token, uint256 _amount); }
set next unlock index
nextUnlockIndex++;
1,374,757
[ 1, 542, 1024, 7186, 770, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 7734, 1024, 7087, 1016, 9904, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x881c72D1e6317f10a1cDCBe05040E7564E790C80/sources/StakingRewardsWithPlatformToken.sol
* @dev Claims outstanding rewards for the sender. Only the native rewards token, and not the platform rewards/
function claimRewardOnly() public updateReward(msg.sender) { uint256 reward = _claimReward(); emit RewardPaid(msg.sender, reward, 0); }
4,139,039
[ 1, 15925, 20974, 283, 6397, 364, 326, 5793, 18, 5098, 326, 6448, 283, 6397, 1147, 16, 471, 486, 326, 4072, 283, 6397, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 17631, 1060, 3386, 1435, 203, 3639, 1071, 203, 3639, 1089, 17631, 1060, 12, 3576, 18, 15330, 13, 203, 565, 288, 203, 3639, 2254, 5034, 19890, 273, 389, 14784, 17631, 1060, 5621, 203, 3639, 3626, 534, 359, 1060, 16507, 350, 12, 3576, 18, 15330, 16, 19890, 16, 374, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xAE69a93945133c00B9985D9361A1cd882d107622/sources/TokenizedStrategy.sol
Mapping of nonces used for permit functions.
mapping(address => uint256) nonces;
16,059,232
[ 1, 3233, 434, 1661, 764, 1399, 364, 21447, 4186, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2874, 12, 2867, 516, 2254, 5034, 13, 1661, 764, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; contract God { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyTokenHolders() { require(myTokens() > 0); _; } // only people with profits modifier onlyProfitsHolders() { require(myDividends(true) > 0); _; } modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event onInjectEtherFromIco(uint _incomingEthereum, uint _dividends, uint profitPerShare_); event onInjectEtherToDividend(address sender, uint _incomingEthereum, uint profitPerShare_); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "God"; string public symbol = "God"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 10; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2 ** 64; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; uint constant internal MIN_TOKEN_TRANSFER = 1e10; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; mapping(address => mapping(address => uint256)) internal allowed; // administrator list (see above on what they can do) address internal owner; mapping(address => bool) public administrators; address bankAddress; mapping(address => bool) public contractAddresses; int internal contractPayout = 0; bool internal isProjectBonus = true; uint internal projectBonus = 0; uint internal projectBonusRate = 10; // 1/10 /*======================================= = PUBLIC FUNCTIONS = =======================================*/ constructor() public { // add administrators here owner = msg.sender; administrators[owner] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns (uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() public payable { purchaseTokens(msg.value, 0x0); } function injectEtherFromIco() public payable { uint _incomingEthereum = msg.value; require(_incomingEthereum > 0); uint256 _dividends = SafeMath.div(_incomingEthereum, dividendFee_); if (isProjectBonus) { uint temp = SafeMath.div(_dividends, projectBonusRate); _dividends = SafeMath.sub(_dividends, temp); projectBonus = SafeMath.add(projectBonus, temp); } profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); emit onInjectEtherFromIco(_incomingEthereum, _dividends, profitPerShare_); } function injectEtherToDividend() public payable { uint _incomingEthereum = msg.value; require(_incomingEthereum > 0); profitPerShare_ += (_incomingEthereum * magnitude / (tokenSupply_)); emit onInjectEtherToDividend(msg.sender, _incomingEthereum, profitPerShare_); } function injectEther() public payable {} /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyProfitsHolders() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyProfitsHolders() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyTokenHolders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); if (isProjectBonus) { uint temp = SafeMath.div(_dividends, projectBonusRate); _dividends = SafeMath.sub(_dividends, temp); projectBonus = SafeMath.add(projectBonus, temp); } // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event emit onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyTokenHolders() public returns (bool) { address _customerAddress = msg.sender; require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); bytes memory empty; transferFromInternal(_customerAddress, _toAddress, _amountOfTokens, empty); return true; } function transferFromInternal(address _from, address _toAddress, uint _amountOfTokens, bytes _data) internal { require(_toAddress != address(0x0)); uint fromLength; uint toLength; assembly { fromLength := extcodesize(_from) toLength := extcodesize(_toAddress) } if (fromLength > 0 && toLength <= 0) { // contract to human contractAddresses[_from] = true; contractPayout -= (int) (_amountOfTokens); tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); } else if (fromLength <= 0 && toLength > 0) { // human to contract contractAddresses[_toAddress] = true; contractPayout += (int) (_amountOfTokens); tokenSupply_ = SafeMath.sub(tokenSupply_, _amountOfTokens); payoutsTo_[_from] -= (int256) (profitPerShare_ * _amountOfTokens); } else if (fromLength > 0 && toLength > 0) { // contract to contract contractAddresses[_from] = true; contractAddresses[_toAddress] = true; } else { // human to human payoutsTo_[_from] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); } // exchange tokens tokenBalanceLedger_[_from] = SafeMath.sub(tokenBalanceLedger_[_from], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // to contract if (toLength > 0) { ERC223Receiving receiver = ERC223Receiving(_toAddress); receiver.tokenFallback(_from, _amountOfTokens, _data); } // fire event emit Transfer(_from, _toAddress, _amountOfTokens); } function transferFrom(address _from, address _toAddress, uint _amountOfTokens) public returns (bool) { // Setup variables address _customerAddress = _from; bytes memory empty; // Make sure we own the tokens we're transferring, are ALLOWED to transfer that many tokens, // and are transferring at least one full token. require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= tokenBalanceLedger_[_customerAddress] && _amountOfTokens <= allowed[_customerAddress][msg.sender]); transferFromInternal(_from, _toAddress, _amountOfTokens, empty); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _amountOfTokens); // Good old ERC20. return true; } function transferTo(address _from, address _to, uint _amountOfTokens, bytes _data) public { if (_from != msg.sender) { require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= tokenBalanceLedger_[_from] && _amountOfTokens <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _amountOfTokens); } else { require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= tokenBalanceLedger_[_from]); } transferFromInternal(_from, _to, _amountOfTokens, _data); } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ function setBank(address _identifier, uint256 value) onlyAdministrator() public { bankAddress = _identifier; contractAddresses[_identifier] = true; tokenBalanceLedger_[_identifier] = value; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { require(_identifier != owner); administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } function getContractPayout() onlyAdministrator() public view returns (int) { return contractPayout; } function getIsProjectBonus() onlyAdministrator() public view returns (bool) { return isProjectBonus; } function setIsProjectBonus(bool value) onlyAdministrator() public { isProjectBonus = value; } function getProjectBonus() onlyAdministrator() public view returns (uint) { return projectBonus; } function takeProjectBonus(address to, uint value) onlyAdministrator() public { require(value <= projectBonus); to.transfer(value); } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns (uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns (uint256) { return tokenSupply_; } // erc 20 function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns (uint256) { address _customerAddress = msg.sender; return getBalance(_customerAddress); } function getProfitPerShare() public view returns (uint256) { return (uint256) ((int256)(tokenSupply_*profitPerShare_)) / magnitude; } function getContractETH() public view returns (uint256) { return address(this).balance; } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns (uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress); } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns (uint256) { if(contractAddresses[_customerAddress]){ return 0; } return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the token balance of any single address. */ function getBalance(address _customerAddress) view public returns (uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns (uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. if (tokenSupply_ == 0) { return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. if (tokenSupply_ == 0) { return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns (uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); if (isProjectBonus) { uint temp = SafeMath.div(_undividedDividends, projectBonusRate); _dividends = SafeMath.sub(_dividends, temp); projectBonus = SafeMath.add(projectBonus, temp); } uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if ( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if (tokenSupply_ > 0) { // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial ** 2) + (2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18)) + (((tokenPriceIncremental_) ** 2) * (tokenSupply_ ** 2)) + (2 * (tokenPriceIncremental_) * _tokenPriceInitial * tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2 ) / 1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } contract ERC223Receiving { function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool); } /** * @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; } }
* Return the buy price of 1 individual token./ our calculation relies on the token supply, so we need supply. Doh.
function sellPrice() public view returns (uint256) { if (tokenSupply_ == 0) { return tokenPriceInitial_ - tokenPriceIncremental_; uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } }
6,305,765
[ 1, 990, 326, 30143, 6205, 434, 404, 7327, 1147, 18, 19, 3134, 11096, 14719, 281, 603, 326, 1147, 14467, 16, 1427, 732, 1608, 14467, 18, 2256, 76, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 357, 80, 5147, 1435, 203, 565, 1071, 203, 565, 1476, 203, 565, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 309, 261, 2316, 3088, 1283, 67, 422, 374, 13, 288, 203, 5411, 327, 1147, 5147, 4435, 67, 300, 1147, 5147, 10798, 287, 67, 31, 203, 5411, 2254, 5034, 389, 546, 822, 379, 273, 2430, 774, 41, 18664, 379, 67, 12, 21, 73, 2643, 1769, 203, 5411, 2254, 5034, 389, 2892, 350, 5839, 273, 14060, 10477, 18, 2892, 24899, 546, 822, 379, 16, 31945, 14667, 67, 1769, 203, 5411, 2254, 5034, 389, 8066, 329, 41, 18664, 379, 273, 14060, 10477, 18, 1717, 24899, 546, 822, 379, 16, 389, 2892, 350, 5839, 1769, 203, 5411, 327, 389, 8066, 329, 41, 18664, 379, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x5b47648AB81131Ec98ac8e63Ca1ca5D89587857B/sources/contracts/slimbase/ERC721Base.sol
Getter for approved or owner
function __isApprovedOrOwner(address spender, uint256 tokenId) external view override onlyInternal returns (bool) { return _isApprovedOrOwner(spender, tokenId); }
12,341,789
[ 1, 8461, 364, 20412, 578, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1001, 291, 31639, 1162, 5541, 12, 2867, 17571, 264, 16, 2254, 5034, 1147, 548, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1338, 3061, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 389, 291, 31639, 1162, 5541, 12, 87, 1302, 264, 16, 1147, 548, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x913A2A71871Faa5e488c539275377edAC3E6D7Cd/sources/contracts/StakingOG.sol
* @dev Reset the rewarded address, to call at each transfer/
function resetRewardedAddress( uint256 tokenId ) internal { if (tokenIdToRewardedAddress[tokenId] != address(0)) tokenIdToRewardedAddress[tokenId] = address(0); }
17,079,409
[ 1, 7013, 326, 283, 11804, 1758, 16, 358, 745, 622, 1517, 7412, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2715, 17631, 17212, 1887, 12, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 2713, 288, 203, 3639, 309, 261, 2316, 28803, 17631, 17212, 1887, 63, 2316, 548, 65, 480, 1758, 12, 20, 3719, 1147, 28803, 17631, 17212, 1887, 63, 2316, 548, 65, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x46baF37b504e24DB0Edd92Cdd5089f737c759a3C/sources/home/vadim/code/skale-manager/contracts/utils/FieldOperations.sol
Current solidity version does not support Constants of non-value type so we implemented this function
function getG2() internal pure returns (G2Point memory) { return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); }
4,341,258
[ 1, 3935, 18035, 560, 1177, 1552, 486, 2865, 5245, 434, 1661, 17, 1132, 618, 1427, 732, 8249, 333, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7162, 22, 1435, 2713, 16618, 1135, 261, 43, 22, 2148, 3778, 13, 288, 203, 3639, 327, 611, 22, 2148, 12590, 203, 5411, 619, 30, 478, 84, 22, 9343, 18, 42, 84, 22, 2148, 12590, 203, 7734, 279, 30, 1728, 7140, 27, 3028, 26, 11984, 3103, 5082, 10321, 3437, 6162, 6334, 25, 7301, 6669, 3787, 1578, 28, 5540, 8875, 3437, 7301, 27, 4313, 4763, 8778, 27, 7140, 18278, 5292, 2733, 6260, 21, 11984, 1578, 28, 4313, 2539, 7140, 5324, 11861, 16, 203, 7734, 324, 30, 4648, 2539, 10580, 31273, 1578, 10689, 4449, 11035, 23054, 2733, 6625, 24, 3103, 24347, 3787, 7140, 8285, 5520, 2947, 28, 2138, 5292, 28246, 23635, 2947, 5082, 29, 28686, 4630, 3600, 30379, 4366, 29, 18278, 4313, 5026, 203, 5411, 289, 3631, 203, 5411, 677, 30, 478, 84, 22, 9343, 18, 42, 84, 22, 2148, 12590, 203, 7734, 279, 30, 1725, 7616, 4313, 25, 5520, 4366, 28462, 23, 3461, 28493, 3028, 10580, 1578, 24, 5608, 6675, 5324, 3247, 17295, 2643, 3657, 6260, 28, 9060, 4449, 28133, 25005, 4700, 3103, 3672, 1105, 29, 5082, 8148, 8204, 15168, 29, 5082, 16, 203, 7734, 324, 30, 1059, 6840, 29941, 8285, 5877, 28, 4449, 24, 3707, 9470, 3437, 1578, 3462, 5026, 4630, 3461, 6564, 23, 2539, 9470, 23, 2313, 7140, 22152, 5877, 29, 5026, 1611, 26825, 21661, 5608, 2163, 6669, 22, 3461, 2138, 713, 29, 4763, 6938, 203, 5411, 289, 13, 203, 3639, 15549, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x1a1C83358AFD86F54eD659109c5448FA6d9Ddc43/sources/lib/openzeppelin-contracts/contracts/access/AccessControl.sol
* @dev Contract module that allows children to implement role-based access control mechanisms. This is a lightweight version that doesn't allow enumerating role members except through off-chain means by accessing the contract event logs. Some applications may benefit from on-chain enumerability, for those cases see {AccessControlEnumerable}. Roles are referred to by their `bytes32` identifier. These should be exposed in the external API and be unique. The best way to achieve this is by using `public constant` hash digests: ```solidity bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); ``` Roles can be used to represent a set of permissions. To restrict access to a function call, use {hasRole}: ```solidity function foo() public { require(hasRole(MY_ROLE, msg.sender)); ... } ``` Roles can be granted and revoked dynamically via the {grantRole} and {revokeRole} functions. Each role has an associated admin role, and only accounts that have a role's admin role can call {grantRole} and {revokeRole}. By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means that only accounts with this role will be able to grant or revoke other roles. More complex role relationships can be created by using {_setRoleAdmin}. WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to grant and revoke this role. Extra precautions should be taken to secure accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules} to enforce additional security measures for this role./
abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; modifier onlyRole(bytes32 role) { _checkRole(role); _; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } function hasRole(bytes32 role, address account) public view virtual returns (bool) { return _roles[role].members[account]; } function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(account), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(account), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) { return _roles[role].adminRole; } function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } }
3,100,760
[ 1, 8924, 1605, 716, 5360, 2325, 358, 2348, 2478, 17, 12261, 2006, 3325, 1791, 28757, 18, 1220, 353, 279, 9052, 4865, 1177, 716, 3302, 1404, 1699, 3557, 1776, 2478, 4833, 1335, 3059, 3397, 17, 5639, 4696, 635, 19531, 326, 6835, 871, 5963, 18, 10548, 12165, 2026, 27641, 7216, 628, 603, 17, 5639, 3557, 2967, 16, 364, 5348, 6088, 2621, 288, 16541, 3572, 25121, 5496, 19576, 854, 29230, 358, 635, 3675, 1375, 3890, 1578, 68, 2756, 18, 8646, 1410, 506, 16265, 316, 326, 3903, 1491, 471, 506, 3089, 18, 1021, 3796, 4031, 358, 20186, 537, 333, 353, 635, 1450, 1375, 482, 5381, 68, 1651, 5403, 87, 30, 31621, 30205, 560, 1731, 1578, 1071, 5381, 22069, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 22114, 67, 16256, 8863, 31621, 19576, 848, 506, 1399, 358, 2406, 279, 444, 434, 4371, 18, 2974, 13108, 2006, 358, 279, 445, 745, 16, 999, 288, 5332, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 17801, 6835, 24349, 353, 1772, 16, 467, 16541, 16, 4232, 39, 28275, 288, 203, 203, 565, 1958, 6204, 751, 288, 203, 3639, 2874, 12, 2867, 516, 1426, 13, 4833, 31, 203, 3639, 1731, 1578, 3981, 2996, 31, 203, 565, 289, 203, 203, 565, 2874, 12, 3890, 1578, 516, 6204, 751, 13, 3238, 389, 7774, 31, 203, 203, 565, 1731, 1578, 1071, 5381, 3331, 67, 15468, 67, 16256, 273, 374, 92, 713, 31, 203, 203, 565, 9606, 1338, 2996, 12, 3890, 1578, 2478, 13, 288, 203, 3639, 389, 1893, 2996, 12, 4615, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1560, 548, 422, 618, 12, 45, 16541, 2934, 5831, 548, 747, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 28335, 12, 3890, 1578, 2478, 16, 1758, 2236, 13, 1071, 1476, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 7774, 63, 4615, 8009, 7640, 63, 4631, 15533, 203, 565, 289, 203, 203, 565, 445, 389, 1893, 2996, 12, 3890, 1578, 2478, 13, 2713, 1476, 5024, 288, 203, 3639, 389, 1893, 2996, 12, 4615, 16, 389, 3576, 12021, 10663, 203, 565, 289, 203, 203, 565, 445, 389, 1893, 2996, 12, 3890, 1578, 2478, 16, 1758, 2236, 13, 2713, 1476, 5024, 288, 203, 3639, 309, 16051, 5332, 2996, 12, 4615, 16, 2236, 3719, 288, 203, 5411, 15226, 12, 203, 7734, 533, 12, 203, 10792, 24126, 2 ]
./full_match/80001/0xC7624Bb655b2A0db2242087607A67B6D1A427676/sources/NftStaking.sol
Make sure the user has at least 1 token staked before withdrawing withdraw must on the token they are trying to withdraw update the rewards for this user, as the amount of rewards decreases with less tokens find the index of this tokens in the stakedTokens array
function withdraw(uint256 _tokenId) external nonReentrant { require( stakers[msg.sender].amountStaked > 1, "You have no tokens staked" ); require(stakerAddress[_tokenId] == msg.sender, "You don't own this tokens"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) { if (stakers[msg.sender].stakedTokens[i].tokenId == _tokenId) { index = i; break; } } stakers[msg.sender].timeOfLastUpdate = block.timestamp; }
5,585,239
[ 1, 6464, 3071, 326, 729, 711, 622, 4520, 404, 1147, 384, 9477, 1865, 598, 9446, 310, 598, 9446, 1297, 603, 326, 1147, 2898, 854, 8374, 358, 598, 9446, 1089, 326, 283, 6397, 364, 333, 729, 16, 487, 326, 3844, 434, 283, 6397, 23850, 3304, 598, 5242, 2430, 1104, 326, 770, 434, 333, 2430, 316, 326, 384, 9477, 5157, 526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 915, 598, 9446, 12, 11890, 5034, 389, 2316, 548, 13, 3903, 1661, 426, 8230, 970, 225, 288, 203, 1377, 2583, 12, 203, 3639, 384, 581, 414, 63, 3576, 18, 15330, 8009, 8949, 510, 9477, 405, 404, 16, 203, 3639, 315, 6225, 1240, 1158, 2430, 384, 9477, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 334, 6388, 1887, 63, 67, 2316, 548, 65, 422, 1234, 18, 15330, 16, 315, 6225, 2727, 1404, 4953, 333, 2430, 8863, 203, 21281, 225, 2254, 5034, 283, 6397, 273, 4604, 17631, 14727, 12, 3576, 18, 15330, 1769, 203, 225, 384, 581, 414, 63, 3576, 18, 15330, 8009, 551, 80, 4581, 329, 17631, 14727, 1011, 283, 6397, 31, 203, 203, 11890, 5034, 770, 273, 374, 31, 203, 1884, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 384, 581, 414, 63, 3576, 18, 15330, 8009, 334, 9477, 5157, 18, 2469, 31, 277, 27245, 288, 203, 282, 309, 261, 334, 581, 414, 63, 3576, 18, 15330, 8009, 334, 9477, 5157, 63, 77, 8009, 2316, 548, 422, 389, 2316, 548, 13, 288, 203, 565, 770, 273, 277, 31, 203, 565, 898, 31, 203, 282, 289, 203, 203, 97, 203, 203, 203, 203, 203, 203, 334, 581, 414, 63, 3576, 18, 15330, 8009, 957, 951, 3024, 1891, 273, 1203, 18, 5508, 31, 203, 203, 203, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "hardhat/console.sol"; import "@openzeppelin/contracts/governance/TimelockController.sol"; import "@openzeppelin/contracts/utils/Multicall.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IShare } from "../interfaces/IShare.sol"; import { IMembership } from "../interfaces/IMembership.sol"; import { IModule } from "../interfaces/IModule.sol"; import { DataTypes } from "../libraries/DataTypes.sol"; import { Errors } from "../libraries/Errors.sol"; import { Events } from "../libraries/Events.sol"; /** * @title Treasury * @notice The treasury is one of the core contracts of the DAO and is responsible for managing all of the DAO's assets, * including external assets, eth and share tokens of the DAO. * the treasury supports external investors in invoking the investment method to self-serve share tokens, * and the treasury provides a hook method for modules to pull payments, * allowing authorization for some of the assets of the modules used by the DAO. */ contract Treasury is TimelockController, Multicall { using Address for address payable; address public immutable share; address public immutable membership; DataTypes.ShareSplit public shareSplit; DataTypes.InvestmentSettings public investmentSettings; address[] private _proposers; address[] private _executors = [address(0)]; mapping(address => uint256) private _investThresholdInERC20; mapping(address => uint256) private _investRatioInERC20; mapping(address => DataTypes.ModulePayment) private _modulePayments; constructor( uint256 timelockDelay, address membershipTokenAddress, address shareTokenAddress, DataTypes.InvestmentSettings memory settings ) TimelockController(timelockDelay, _proposers, _executors) { membership = membershipTokenAddress; share = shareTokenAddress; investmentSettings = settings; _mappingSettings(settings); } modifier investmentEnabled() { if (!investmentSettings.enableInvestment) revert Errors.InvestmentDisabled(); _; } /** * @dev Shortcut method * Allows distribution of shares to members in corresponding proportions (index is tokenID) * must be called by the timelock itself (requires a voting process) */ function vestingShare(uint256[] calldata tokenId, uint8[] calldata shareRatio) public onlyRole(TIMELOCK_ADMIN_ROLE) { uint256 _shareTreasury = IShare(share).balanceOf(address(this)); if (_shareTreasury == 0) revert Errors.NoShareInTreasury(); uint256 _membersShare = _shareTreasury * (shareSplit.members / 100); if (_membersShare == 0) revert Errors.NoMembersShareToVest(); for (uint256 i = 0; i < tokenId.length; i++) { address _member = IMembership(membership).ownerOf(tokenId[i]); IShare(share).transfer(_member, (_membersShare * shareRatio[i]) / 100); } } /** * @dev Shortcut method * to update settings for investment (requires a voting process) */ function updateInvestmentSettings( DataTypes.InvestmentSettings memory settings ) public onlyRole(TIMELOCK_ADMIN_ROLE) { investmentSettings = settings; _mappingSettings(settings); } /** * @dev Shortcut method * to update share split (requires a voting process) */ function updateShareSplit(DataTypes.ShareSplit memory _shareSplit) public onlyRole(TIMELOCK_ADMIN_ROLE) { shareSplit = _shareSplit; } /** * @dev Invest in ETH * Allows external investors to transfer to ETH for investment. * ETH will issue share token of DAO at a set rate */ function invest() external payable investmentEnabled { if (investmentSettings.investRatioInETH == 0) revert Errors.InvestmentDisabled(); if (msg.value < investmentSettings.investThresholdInETH) revert Errors.InvestmentThresholdNotMet( investmentSettings.investThresholdInETH ); _invest( msg.value / investmentSettings.investRatioInETH, address(0), msg.value ); } /** * @dev Invest in ERC20 tokens * External investors are allowed to invest in ERC20, * which is issued as a DAO share token at a set rate. * @notice Before calling this method, the approve method of the corresponding ERC20 contract must be called. */ function investInERC20(address token) external investmentEnabled { if (_investRatioInERC20[token] == 0) revert Errors.InvestmentInERC20Disabled(token); uint256 _radio = _investRatioInERC20[token]; if (_radio == 0) revert Errors.InvestmentInERC20Disabled(token); uint256 _threshold = _investThresholdInERC20[token]; uint256 _allowance = IShare(token).allowance(_msgSender(), address(this)); if (_allowance < _threshold) revert Errors.InvestmentInERC20ThresholdNotMet(token, _threshold); IShare(token).transferFrom(_msgSender(), address(this), _allowance); _invest(_allowance / _radio, token, _allowance); } /** * @dev Pull module payment * The DAO module pulls the required eth and ERC20 token * @notice Need to ensure that the number of authorizations is greater than the required number before pulling. * this method is usually required by the module designer, * and the method checks whether the module is mounted on the same DAO */ function pullModulePayment( uint256 eth, address[] calldata tokens, uint256[] calldata amounts ) public { if (tokens.length != amounts.length) revert Errors.InvalidTokenAmounts(); address moduleAddress = _msgSender(); if (IModule(moduleAddress).membership() != membership) revert Errors.NotMember(); DataTypes.ModulePayment storage _payments = _modulePayments[moduleAddress]; address _timelock = address(IModule(moduleAddress).timelock()); address payable _target = payable(_timelock); if (!_payments.approved) revert Errors.ModuleNotApproved(); if (eth > 0) { if (eth > _payments.eth) revert Errors.NotEnoughETH(); _payments.eth -= eth; _target.sendValue(eth); } for (uint256 i = 0; i < tokens.length; i++) { IERC20 _token = IERC20(tokens[i]); if (_token.allowance(address(this), _timelock) < amounts[i]) revert Errors.NotEnoughTokens(); _token.transferFrom(address(this), _timelock, amounts[i]); _payments.erc20[tokens[i]] -= amounts[i]; } emit Events.ModulePaymentPulled( moduleAddress, eth, tokens, amounts, block.timestamp ); } /** * @dev Approve module payment * Authorize a module to use the corresponding eth and ERC20 token */ function approveModulePayment( address moduleAddress, uint256 eth, address[] calldata tokens, uint256[] calldata amounts ) public onlyRole(TIMELOCK_ADMIN_ROLE) { if (tokens.length != amounts.length) revert Errors.InvalidTokenAmounts(); if (IModule(moduleAddress).membership() != membership) revert Errors.NotMember(); DataTypes.ModulePayment storage _payments = _modulePayments[moduleAddress]; _payments.approved = true; _payments.eth = eth; for (uint256 i = 0; i < tokens.length; i++) { IERC20 _token = IERC20(tokens[i]); if (_token.balanceOf(address(this)) < amounts[i]) revert Errors.NotEnoughTokens(); _payments.erc20[tokens[i]] = amounts[i]; _token.approve(address(IModule(moduleAddress).timelock()), amounts[i]); } emit Events.ModulePaymentApproved( moduleAddress, eth, tokens, amounts, block.timestamp ); } /** * @dev Private method of realizing external investments * The converted share token is automatically transferred to the external investor, * and if there are not enough shares in the vault, additional shares are automatically issued. * At the same time, the act of investing will mint a new investor status NFT membership card, * ensuring that the investor can participate in the voting of board members (1/1 NFT Votes). */ function _invest( uint256 _shareTobeClaimed, address _token, uint256 _amount ) private { uint256 _shareTreasury = IShare(share).balanceOf(address(this)); if (_shareTreasury < _shareTobeClaimed) { IShare(share).mint(address(this), _shareTobeClaimed - _shareTreasury); } IShare(share).transfer(_msgSender(), _shareTobeClaimed); IMembership(membership).investMint(_msgSender()); if (_token == address(0)) { emit Events.InvestInETH(_msgSender(), msg.value, _shareTobeClaimed); } else { emit Events.InvestInERC20( _msgSender(), _token, _amount, _shareTobeClaimed ); } } // @dev mapping arrays to maps cause of the lack of support of params mapping in Solidity function _mappingSettings(DataTypes.InvestmentSettings memory settings) private { if (settings.investInERC20.length > 0) { for (uint256 i = 0; i < settings.investInERC20.length; i++) { address _token = settings.investInERC20[i]; _investThresholdInERC20[_token] = settings.investThresholdInERC20[i]; _investRatioInERC20[_token] = settings.investRatioInERC20[i]; } } } }
* @dev Pull module payment The DAO module pulls the required eth and ERC20 token @notice Need to ensure that the number of authorizations is greater than the required number before pulling. this method is usually required by the module designer, and the method checks whether the module is mounted on the same DAO/
function pullModulePayment( uint256 eth, address[] calldata tokens, uint256[] calldata amounts ) public { if (tokens.length != amounts.length) revert Errors.InvalidTokenAmounts(); address moduleAddress = _msgSender(); if (IModule(moduleAddress).membership() != membership) revert Errors.NotMember(); DataTypes.ModulePayment storage _payments = _modulePayments[moduleAddress]; address _timelock = address(IModule(moduleAddress).timelock()); address payable _target = payable(_timelock); if (!_payments.approved) revert Errors.ModuleNotApproved(); if (eth > 0) { if (eth > _payments.eth) revert Errors.NotEnoughETH(); _payments.eth -= eth; _target.sendValue(eth); } for (uint256 i = 0; i < tokens.length; i++) { IERC20 _token = IERC20(tokens[i]); if (_token.allowance(address(this), _timelock) < amounts[i]) revert Errors.NotEnoughTokens(); _token.transferFrom(address(this), _timelock, amounts[i]); _payments.erc20[tokens[i]] -= amounts[i]; } emit Events.ModulePaymentPulled( moduleAddress, eth, tokens, amounts, block.timestamp ); }
2,520,458
[ 1, 9629, 1605, 5184, 1021, 463, 20463, 1605, 6892, 87, 326, 1931, 13750, 471, 4232, 39, 3462, 1147, 225, 12324, 358, 3387, 716, 326, 1300, 434, 2869, 7089, 353, 6802, 2353, 326, 1931, 1300, 1865, 6892, 310, 18, 333, 707, 353, 11234, 1931, 635, 326, 1605, 8281, 264, 16, 471, 326, 707, 4271, 2856, 326, 1605, 353, 20919, 603, 326, 1967, 463, 20463, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 6892, 3120, 6032, 12, 203, 565, 2254, 5034, 13750, 16, 203, 565, 1758, 8526, 745, 892, 2430, 16, 203, 565, 2254, 5034, 8526, 745, 892, 30980, 203, 225, 262, 1071, 288, 203, 565, 309, 261, 7860, 18, 2469, 480, 30980, 18, 2469, 13, 15226, 9372, 18, 1941, 1345, 6275, 87, 5621, 203, 203, 565, 1758, 1605, 1887, 273, 389, 3576, 12021, 5621, 203, 565, 309, 261, 45, 3120, 12, 2978, 1887, 2934, 19679, 1435, 480, 12459, 13, 203, 1377, 15226, 9372, 18, 1248, 4419, 5621, 203, 203, 565, 1910, 2016, 18, 3120, 6032, 2502, 389, 10239, 1346, 273, 389, 2978, 23725, 63, 2978, 1887, 15533, 203, 565, 1758, 389, 8584, 292, 975, 273, 1758, 12, 45, 3120, 12, 2978, 1887, 2934, 8584, 292, 975, 10663, 203, 565, 1758, 8843, 429, 389, 3299, 273, 8843, 429, 24899, 8584, 292, 975, 1769, 203, 203, 565, 309, 16051, 67, 10239, 1346, 18, 25990, 13, 15226, 9372, 18, 3120, 1248, 31639, 5621, 203, 203, 565, 309, 261, 546, 405, 374, 13, 288, 203, 1377, 309, 261, 546, 405, 389, 10239, 1346, 18, 546, 13, 15226, 9372, 18, 1248, 664, 4966, 1584, 44, 5621, 203, 1377, 389, 10239, 1346, 18, 546, 3947, 13750, 31, 203, 1377, 389, 3299, 18, 4661, 620, 12, 546, 1769, 203, 565, 289, 203, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2430, 18, 2469, 31, 277, 27245, 288, 203, 1377, 467, 654, 39, 3462, 389, 2316, 273, 467, 654, 39, 3462, 12, 7860, 63, 77, 19226, 203, 1377, 2 ]
// SPDX-License-Identifier: MIT // IonTimelock.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IIonxTimelock.sol"; import "../lib/BlackholePrevention.sol"; contract IonxTimelock is IIonxTimelock, BlackholePrevention { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public token; address public funder; address public receiver; Portion[] public portions; uint256 public totalAmountInTimelock; bool public activated; /***********************************| | Initialization | |__________________________________*/ constructor (address _funder, address _receiver, address _token) public { require(_funder != address(0x0), "ITL:E-403"); require(_receiver != address(0x0), "ITL:E-403"); require(_token != address(0x0), "ITL:E-403"); token = IERC20(_token); funder = _funder; receiver = _receiver; } /***********************************| | Public | |__________________________________*/ function addPortions(uint256[] memory amounts, uint256[] memory releaseTimes) external virtual override onlyFunder returns (bool) { require(amounts.length == releaseTimes.length, "ITL:E-202"); for (uint i = 0; i < amounts.length; i++) { uint256 releaseTime = releaseTimes[i]; if (i > 0) { require(releaseTimes[i] > releaseTimes[i - 1], "ITL:E-204"); } uint256 amount = amounts[i]; // solhint-disable-next-line not-rely-on-time require(releaseTime > block.timestamp, "ITL:E-301"); portions.push(Portion({ amount: amount, releaseTime: releaseTime, claimed: false })); totalAmountInTimelock = totalAmountInTimelock.add(amount); } uint256 amountAvailable = token.balanceOf(address(this)); require(amountAvailable >= totalAmountInTimelock, "ITL:E-411"); emit PortionsAdded(amounts, releaseTimes); return true; } /** * @return releaseTime The time when the next portion of tokens will be released. */ function nextReleaseTime() external view virtual override returns (uint256 releaseTime) { uint256 portionCount = portions.length; for (uint i = 0; i < portionCount; i++) { // solhint-disable-next-line not-rely-on-time if (portions[i].releaseTime > block.timestamp) { releaseTime = portions[i].releaseTime; break; } } } /** * @return releaseAmount The next amount that will be released. */ function nextReleaseAmount() external view virtual override returns (uint256 releaseAmount) { uint256 portionCount = portions.length; for (uint i = 0; i < portionCount; i++) { // solhint-disable-next-line not-rely-on-time if (portions[i].releaseTime > block.timestamp) { releaseAmount = portions[i].amount; break; } } } /** * @notice Transfers tokens held by timelock to the receiver. */ function release(uint256 numPortions, uint256 indexOffset) external virtual override onlyWhenActivated returns (uint256 amount) { require(numPortions <= portions.length, "ITL:E-201"); uint256 portionCount = numPortions > 0 ? numPortions : portions.length; for (uint i = indexOffset; i < portionCount; i++) { // solhint-disable-next-line not-rely-on-time if (!portions[i].claimed && portions[i].releaseTime <= block.timestamp) { amount = amount.add(portions[i].amount); portions[i].claimed = true; emit PortionReleased(portions[i].amount, portions[i].releaseTime); } } uint256 amountAvailable = token.balanceOf(address(this)); require(amount <= amountAvailable, "ITL:E-411"); totalAmountInTimelock = amountAvailable.sub(amount); token.safeTransfer(receiver, amount); } /** * @notice Transfers tokens held by timelock to the receiver. */ function releasePortion(uint256 portionIndex) external virtual override onlyWhenActivated returns (uint256 amount) { require(portionIndex >= 0 && portionIndex < portions.length, "ITL:E-201"); Portion memory _portion = portions[portionIndex]; require(!_portion.claimed, "ITL:E-431"); // solhint-disable-next-line not-rely-on-time require(_portion.releaseTime <= block.timestamp, "ITL:E-302"); amount = _portion.amount; portions[portionIndex].claimed = true; uint256 amountAvailable = token.balanceOf(address(this)); require(amount <= amountAvailable, "ITL:E-411"); totalAmountInTimelock = amountAvailable.sub(amount); token.safeTransfer(receiver, amount); emit PortionReleased(_portion.amount, _portion.releaseTime); } function withdrawEther(uint256 amount) external { _withdrawEther(payable(receiver), amount); } function withdrawErc20(address tokenAddress, uint256 amount) external { require(tokenAddress != address(token), "ITL:E-417"); _withdrawERC20(payable(receiver), tokenAddress, amount); } function withdrawERC721(address tokenAddress, uint256 tokenId) external { require(tokenAddress != address(token), "ITL:E-417"); _withdrawERC721(payable(receiver), tokenAddress, tokenId); } function activateTimelock() external virtual override onlyFunder { activated = true; } function destroyTimelock() external virtual override onlyFunder { require(!activated, "ITL:E-115"); uint256 fullAmount = token.balanceOf(address(this)); token.safeTransfer(funder, fullAmount); selfdestruct(payable(funder)); } modifier onlyFunder() { require(msg.sender == funder, "ITL:E-103"); _; } modifier onlyWhenActivated() { require(activated, "ITL:E-116"); _; } }
* @return releaseTime The time when the next portion of tokens will be released./ solhint-disable-next-line not-rely-on-time
function nextReleaseTime() external view virtual override returns (uint256 releaseTime) { uint256 portionCount = portions.length; for (uint i = 0; i < portionCount; i++) { if (portions[i].releaseTime > block.timestamp) { releaseTime = portions[i].releaseTime; break; } } }
12,915,637
[ 1, 2463, 3992, 950, 1021, 813, 1347, 326, 1024, 14769, 434, 2430, 903, 506, 15976, 18, 19, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 486, 17, 266, 715, 17, 265, 17, 957, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1024, 7391, 950, 1435, 203, 565, 3903, 203, 565, 1476, 203, 565, 5024, 203, 565, 3849, 203, 565, 1135, 261, 11890, 5034, 3992, 950, 13, 203, 225, 288, 203, 565, 2254, 5034, 14769, 1380, 273, 1756, 1115, 18, 2469, 31, 203, 565, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 14769, 1380, 31, 277, 27245, 288, 203, 1377, 309, 261, 655, 1115, 63, 77, 8009, 9340, 950, 405, 1203, 18, 5508, 13, 288, 203, 3639, 3992, 950, 273, 1756, 1115, 63, 77, 8009, 9340, 950, 31, 203, 3639, 898, 31, 203, 1377, 289, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// contracts/EarthFundVesting.sol // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } 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); } } } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /** * @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; } } /** * @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); } } /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * @title EarthFundVesting */ contract EarthFundVesting is Ownable, ReentrancyGuard{ using SafeMath for uint256; using SafeERC20 for IERC20; struct VestingSchedule{ bool initialized; // beneficiary of tokens after they are released address beneficiary; // cliff period in seconds uint256 cliff; // start time of the vesting period uint256 start; // duration of the vesting period in seconds uint256 duration; // duration of a slice period for the vesting in seconds uint256 slicePeriodSeconds; // whether or not the vesting is revocable bool revocable; // total amount of tokens to be released at the end of the vesting uint256 amountTotal; // amount of tokens released uint256 released; // whether or not the vesting has been revoked bool revoked; } event VestingScheduleCreated( address beneficiary, uint256 start, uint256 cliff, uint256 duration, uint256 slicePeriodSeconds, bool revocable, uint256 amount ); event Revoked(bytes32 vestingScheduleId); event Withdrawn(uint256 amount); event Released(bytes32 vestingScheduleId, uint256 amount); // address of the ERC20 token IERC20 immutable private _token; bytes32[] private vestingSchedulesIds; mapping(bytes32 => VestingSchedule) private vestingSchedules; uint256 private vestingSchedulesTotalAmount; mapping(address => uint256) private holdersVestingCount; /** * @dev Reverts if no vesting schedule matches the passed identifier. */ modifier onlyIfVestingScheduleExists(bytes32 vestingScheduleId) { require(vestingSchedules[vestingScheduleId].initialized == true); _; } /** * @dev Reverts if the vesting schedule does not exist or has been revoked. */ modifier onlyIfVestingScheduleNotRevoked(bytes32 vestingScheduleId) { require(vestingSchedules[vestingScheduleId].initialized == true); require(vestingSchedules[vestingScheduleId].revoked == false); _; } /** * @dev Creates a vesting contract. * @param token_ address of the ERC20 token contract */ constructor(address token_) { require(token_ != address(0x0)); _token = IERC20(token_); } receive() external payable {} fallback() external payable {} /** * @dev Returns the number of vesting schedules associated to a beneficiary. * @return the number of vesting schedules */ function getVestingSchedulesCountByBeneficiary(address _beneficiary) external view returns(uint256){ return holdersVestingCount[_beneficiary]; } /** * @dev Returns the vesting schedule id at the given index. * @return the vesting id */ function getVestingIdAtIndex(uint256 index) external view returns(bytes32){ require(index < getVestingSchedulesCount(), "EarthFundVesting: index out of bounds"); return vestingSchedulesIds[index]; } /** * @notice Returns the vesting schedule information for a given holder and index. * @return the vesting schedule structure information */ function getVestingScheduleByAddressAndIndex(address holder, uint256 index) external view returns(VestingSchedule memory){ return getVestingSchedule(computeVestingScheduleIdForAddressAndIndex(holder, index)); } /** * @notice Returns the total amount of vesting schedules. * @return the total amount of vesting schedules */ function getVestingSchedulesTotalAmount() external view returns(uint256){ return vestingSchedulesTotalAmount; } /** * @dev Returns the address of the ERC20 token managed by the vesting contract. */ function getToken() external view returns(address){ return address(_token); } /** * @notice Creates a new vesting schedule for a beneficiary. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _start start time of the vesting period * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _slicePeriodSeconds duration of a slice period for the vesting in seconds * @param _revocable whether the vesting is revocable or not * @param _amount total amount of tokens to be released at the end of the vesting */ function createVestingSchedule( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, uint256 _slicePeriodSeconds, bool _revocable, uint256 _amount ) public onlyOwner{ require( this.getWithdrawableAmount() >= _amount, "EarthFundVesting: cannot create vesting schedule because not sufficient tokens" ); require(_duration > 0, "EarthFundVesting: duration must be > 0"); require(_amount > 0, "EarthFundVesting: amount must be > 0"); require(_slicePeriodSeconds >= 1, "EarthFundVesting: slicePeriodSeconds must be >= 1"); bytes32 vestingScheduleId = this.computeNextVestingScheduleIdForHolder(_beneficiary); uint256 cliff = _start.add(_cliff); vestingSchedules[vestingScheduleId] = VestingSchedule( true, _beneficiary, cliff, _start, _duration, _slicePeriodSeconds, _revocable, _amount, 0, false ); vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.add(_amount); vestingSchedulesIds.push(vestingScheduleId); uint256 currentVestingCount = holdersVestingCount[_beneficiary]; holdersVestingCount[_beneficiary] = currentVestingCount.add(1); emit VestingScheduleCreated( _beneficiary, _start, _cliff, _duration, _slicePeriodSeconds, _revocable, _amount ); } /** * @notice Revokes the vesting schedule for given identifier. * @param vestingScheduleId the vesting schedule identifier */ function revoke(bytes32 vestingScheduleId) public onlyOwner onlyIfVestingScheduleNotRevoked(vestingScheduleId){ VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId]; require(vestingSchedule.revocable == true, "EarthFundVesting: vesting is not revocable"); uint256 vestedAmount = _computeReleasableAmount(vestingSchedule); if(vestedAmount > 0){ release(vestingScheduleId, vestedAmount); } uint256 unreleased = vestingSchedule.amountTotal.sub(vestingSchedule.released); vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.sub(unreleased); vestingSchedule.revoked = true; emit Revoked(vestingScheduleId); } /** * @notice Withdraw the specified amount if possible. * @param amount the amount to withdraw */ function withdraw(uint256 amount) public nonReentrant onlyOwner{ require(this.getWithdrawableAmount() >= amount, "EarthFundVesting: not enough withdrawable funds"); _token.safeTransfer(owner(), amount); emit Withdrawn(amount); } /** * @notice Release vested amount of tokens. * @param vestingScheduleId the vesting schedule identifier * @param amount the amount to release */ function release( bytes32 vestingScheduleId, uint256 amount ) public nonReentrant onlyIfVestingScheduleNotRevoked(vestingScheduleId){ VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId]; bool isBeneficiary = msg.sender == vestingSchedule.beneficiary; bool isOwner = msg.sender == owner(); require( isBeneficiary || isOwner, "EarthFundVesting: only beneficiary and owner can release vested tokens" ); uint256 vestedAmount = _computeReleasableAmount(vestingSchedule); require(vestedAmount >= amount, "EarthFundVesting: cannot release tokens, not enough vested tokens"); vestingSchedule.released = vestingSchedule.released.add(amount); address payable beneficiaryPayable = payable(vestingSchedule.beneficiary); vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.sub(amount); _token.safeTransfer(beneficiaryPayable, amount); emit Released(vestingScheduleId, amount); } /** * @dev Returns the number of vesting schedules managed by this contract. * @return the number of vesting schedules */ function getVestingSchedulesCount() public view returns(uint256){ return vestingSchedulesIds.length; } /** * @notice Computes the vested amount of tokens for the given vesting schedule identifier. * @return the vested amount */ function computeReleasableAmount(bytes32 vestingScheduleId) public onlyIfVestingScheduleNotRevoked(vestingScheduleId) view returns(uint256){ VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId]; return _computeReleasableAmount(vestingSchedule); } /** * @notice Returns the vesting schedule information for a given identifier. * @return the vesting schedule structure information */ function getVestingSchedule(bytes32 vestingScheduleId) public view returns(VestingSchedule memory){ return vestingSchedules[vestingScheduleId]; } /** * @dev Returns the amount of tokens that can be withdrawn by the owner. * @return the amount of tokens */ function getWithdrawableAmount() public view returns(uint256){ return _token.balanceOf(address(this)).sub(vestingSchedulesTotalAmount); } /** * @dev Computes the next vesting schedule identifier for a given holder address. */ function computeNextVestingScheduleIdForHolder(address holder) public view returns(bytes32){ return computeVestingScheduleIdForAddressAndIndex(holder, holdersVestingCount[holder]); } /** * @dev Returns the last vesting schedule for a given holder address. */ function getLastVestingScheduleForHolder(address holder) public view returns(VestingSchedule memory){ return vestingSchedules[computeVestingScheduleIdForAddressAndIndex(holder, holdersVestingCount[holder] - 1)]; } /** * @dev Computes the vesting schedule identifier for an address and an index. */ function computeVestingScheduleIdForAddressAndIndex(address holder, uint256 index) public pure returns(bytes32){ return keccak256(abi.encodePacked(holder, index)); } /** * @dev Computes the releasable amount of tokens for a vesting schedule. * @return the amount of releasable tokens */ function _computeReleasableAmount(VestingSchedule memory vestingSchedule) internal view returns(uint256){ uint256 currentTime = getCurrentTime(); if ((currentTime < vestingSchedule.cliff) || vestingSchedule.revoked == true) { return 0; } else if (currentTime >= vestingSchedule.start.add(vestingSchedule.duration)) { return vestingSchedule.amountTotal.sub(vestingSchedule.released); } else { uint256 timeFromStart = currentTime.sub(vestingSchedule.start); uint256 secondsPerSlice = vestingSchedule.slicePeriodSeconds; uint256 vestedSlicePeriods = timeFromStart.div(secondsPerSlice); uint256 vestedSeconds = vestedSlicePeriods.mul(secondsPerSlice); uint256 vestedAmount = vestingSchedule.amountTotal.mul(vestedSeconds).div(vestingSchedule.duration); vestedAmount = vestedAmount.sub(vestingSchedule.released); return vestedAmount; } } function getCurrentTime() internal virtual view returns(uint256){ return block.timestamp; } }
* @notice Revokes the vesting schedule for given identifier. @param vestingScheduleId the vesting schedule identifier/
function revoke(bytes32 vestingScheduleId) public onlyOwner onlyIfVestingScheduleNotRevoked(vestingScheduleId){ VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId]; require(vestingSchedule.revocable == true, "EarthFundVesting: vesting is not revocable"); uint256 vestedAmount = _computeReleasableAmount(vestingSchedule); if(vestedAmount > 0){ release(vestingScheduleId, vestedAmount); } uint256 unreleased = vestingSchedule.amountTotal.sub(vestingSchedule.released); vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.sub(unreleased); vestingSchedule.revoked = true; emit Revoked(vestingScheduleId); }
1,009,710
[ 1, 10070, 601, 281, 326, 331, 10100, 4788, 364, 864, 2756, 18, 225, 331, 10100, 6061, 548, 326, 331, 10100, 4788, 2756, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18007, 12, 3890, 1578, 331, 10100, 6061, 548, 13, 203, 3639, 1071, 203, 3639, 1338, 5541, 203, 3639, 1338, 2047, 58, 10100, 6061, 1248, 10070, 14276, 12, 90, 10100, 6061, 548, 15329, 203, 3639, 776, 10100, 6061, 2502, 331, 10100, 6061, 273, 331, 10100, 27073, 63, 90, 10100, 6061, 548, 15533, 203, 3639, 2583, 12, 90, 10100, 6061, 18, 9083, 504, 429, 422, 638, 16, 315, 41, 27076, 42, 1074, 58, 10100, 30, 331, 10100, 353, 486, 5588, 504, 429, 8863, 203, 3639, 2254, 5034, 331, 3149, 6275, 273, 389, 9200, 17018, 345, 429, 6275, 12, 90, 10100, 6061, 1769, 203, 3639, 309, 12, 90, 3149, 6275, 405, 374, 15329, 203, 5411, 3992, 12, 90, 10100, 6061, 548, 16, 331, 3149, 6275, 1769, 203, 3639, 289, 203, 3639, 2254, 5034, 640, 9340, 72, 273, 331, 10100, 6061, 18, 8949, 5269, 18, 1717, 12, 90, 10100, 6061, 18, 9340, 72, 1769, 203, 3639, 331, 10100, 27073, 5269, 6275, 273, 331, 10100, 27073, 5269, 6275, 18, 1717, 12, 318, 9340, 72, 1769, 203, 3639, 331, 10100, 6061, 18, 9083, 14276, 273, 638, 31, 203, 3639, 3626, 14477, 14276, 12, 90, 10100, 6061, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x60CcE9764F55298cbB54a04E408Cd1CD06061aa0/sources/@openzeppelin/contracts/ownership/Ownable.sol
* @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be 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); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return _msgSender() == _owner; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
3,876,143
[ 1, 8924, 1605, 1492, 8121, 279, 5337, 2006, 3325, 12860, 16, 1625, 1915, 353, 392, 2236, 261, 304, 3410, 13, 716, 848, 506, 17578, 12060, 2006, 358, 2923, 4186, 18, 1220, 1605, 353, 1399, 3059, 16334, 18, 2597, 903, 1221, 2319, 326, 9606, 1375, 3700, 5541, 9191, 1492, 848, 506, 6754, 358, 3433, 4186, 358, 13108, 3675, 999, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 6914, 353, 1772, 288, 203, 565, 1758, 225, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 565, 3885, 1832, 2713, 288, 203, 3639, 1758, 1234, 12021, 273, 389, 3576, 12021, 5621, 203, 3639, 389, 8443, 273, 1234, 12021, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 1234, 12021, 1769, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 291, 5541, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 353, 5541, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 3576, 12021, 1435, 422, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 3639, 389, 8443, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 5024, 1338, 5541, 288, 203, 3639, 389, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 5460, 12565, 12, 2867, 394, 5541, 13, 2713, 5024, 288, 203, 3639, 2583, 12, 2704, 5541, 480, 2 ]
./partial_match/1/0x989E1Fb123b67afd66e10574c8B409bC6e812D9A/sources/DragonCore.sol
event Transfer(address from, address to, uint256 tokenId, uint32 generation);
contract DragonBase is DragonAccessControl, DragonERC721 { event Birth(address owner, uint256 dragonId, uint256 matronId, uint256 sireId, uint256 dna, uint32 generation, uint64 runeLevel); event DragonAssetsUpdated(uint256 _dragonId, uint64 _rune, uint64 _agility, uint64 _strength, uint64 _intelligence); event DragonAssetRequest(uint256 _dragonId); struct Dragon { uint256 dna; uint64 birthTime; uint64 breedTime; uint32 matronId; uint32 sireId; uint32 siringWithId; uint32 generation; } struct DragonAssets { uint64 runeLevel; uint64 agility; uint64 strength; uint64 intelligence; } Dragon[] dragons; mapping (uint256 => address) public dragonIndexToOwner; mapping (address => uint256) ownershipTokenCount; mapping (uint256 => address) public dragonIndexToApproved; mapping (uint256 => address) public sireAllowedToAddress; mapping (uint256 => DragonAssets) public dragonAssets; mapping (address => mapping (address => bool)) internal authorised; uint256 public updateAssetFee = 8 finney; SaleClockAuction public saleAuction; SiringClockAuction public siringAuction; modifier isValidToken(uint256 _tokenId) { require(dragonIndexToOwner[_tokenId] != address(0)); _; } function _transfer(address _from, address _to, uint256 _tokenId) internal { ownershipTokenCount[_to]++; dragonIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; delete sireAllowedToAddress[_tokenId]; delete dragonIndexToApproved[_tokenId]; } } function _transfer(address _from, address _to, uint256 _tokenId) internal { ownershipTokenCount[_to]++; dragonIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; delete sireAllowedToAddress[_tokenId]; delete dragonIndexToApproved[_tokenId]; } } emit Transfer(_from, _to, _tokenId); function _createDragon( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _dna, uint64 _agility, uint64 _strength, uint64 _intelligence, uint64 _runelevel, address _owner ) internal returns (uint) { require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint32(_generation))); Dragon memory _dragon = Dragon({ dna: _dna, birthTime: uint64(now), breedTime: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, generation: uint32(_generation) }); DragonAssets memory _dragonAssets = DragonAssets({ runeLevel: _runelevel, agility: _agility, strength: _strength, intelligence: _intelligence }); uint256 newDragonId = dragons.push(_dragon) - 1; dragonAssets[newDragonId] = _dragonAssets; _owner, newDragonId, uint256(_dragon.matronId), uint256(_dragon.sireId), _dragon.dna, _dragon.generation, _runelevel ); return newDragonId; } function _createDragon( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _dna, uint64 _agility, uint64 _strength, uint64 _intelligence, uint64 _runelevel, address _owner ) internal returns (uint) { require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint32(_generation))); Dragon memory _dragon = Dragon({ dna: _dna, birthTime: uint64(now), breedTime: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, generation: uint32(_generation) }); DragonAssets memory _dragonAssets = DragonAssets({ runeLevel: _runelevel, agility: _agility, strength: _strength, intelligence: _intelligence }); uint256 newDragonId = dragons.push(_dragon) - 1; dragonAssets[newDragonId] = _dragonAssets; _owner, newDragonId, uint256(_dragon.matronId), uint256(_dragon.sireId), _dragon.dna, _dragon.generation, _runelevel ); return newDragonId; } function _createDragon( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _dna, uint64 _agility, uint64 _strength, uint64 _intelligence, uint64 _runelevel, address _owner ) internal returns (uint) { require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint32(_generation))); Dragon memory _dragon = Dragon({ dna: _dna, birthTime: uint64(now), breedTime: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, generation: uint32(_generation) }); DragonAssets memory _dragonAssets = DragonAssets({ runeLevel: _runelevel, agility: _agility, strength: _strength, intelligence: _intelligence }); uint256 newDragonId = dragons.push(_dragon) - 1; dragonAssets[newDragonId] = _dragonAssets; _owner, newDragonId, uint256(_dragon.matronId), uint256(_dragon.sireId), _dragon.dna, _dragon.generation, _runelevel ); return newDragonId; } require(newDragonId == uint256(uint32(newDragonId))); emit Birth( _transfer(address(0), _owner, newDragonId); function setUpdateAssetFee(uint256 newFee) external onlyCLevel { updateAssetFee = newFee; } function updateDragonAsset(uint256 _dragonId, uint64 _rune, uint64 _agility, uint64 _strength, uint64 _intelligence) external whenNotPaused onlyCOO { DragonAssets storage currentDragonAsset = dragonAssets[_dragonId]; require(_rune > currentDragonAsset.runeLevel); require(_agility >= currentDragonAsset.agility); require(_strength >= currentDragonAsset.strength); require(_intelligence >= currentDragonAsset.intelligence); DragonAssets memory _dragonAsset = DragonAssets({ runeLevel: _rune, agility: _agility, strength: _strength, intelligence: _intelligence }); dragonAssets[_dragonId] = _dragonAsset; msg.sender.transfer(updateAssetFee); emit DragonAssetsUpdated(_dragonId, _rune, _agility, _strength, _intelligence); } function updateDragonAsset(uint256 _dragonId, uint64 _rune, uint64 _agility, uint64 _strength, uint64 _intelligence) external whenNotPaused onlyCOO { DragonAssets storage currentDragonAsset = dragonAssets[_dragonId]; require(_rune > currentDragonAsset.runeLevel); require(_agility >= currentDragonAsset.agility); require(_strength >= currentDragonAsset.strength); require(_intelligence >= currentDragonAsset.intelligence); DragonAssets memory _dragonAsset = DragonAssets({ runeLevel: _rune, agility: _agility, strength: _strength, intelligence: _intelligence }); dragonAssets[_dragonId] = _dragonAsset; msg.sender.transfer(updateAssetFee); emit DragonAssetsUpdated(_dragonId, _rune, _agility, _strength, _intelligence); } function requestAssetUpdate(uint256 _dragonId, uint256 _rune) external payable whenNotPaused { require(msg.value >= updateAssetFee); DragonAssets storage currentDragonAsset = dragonAssets[_dragonId]; require(_rune > currentDragonAsset.runeLevel); emit DragonAssetRequest(_dragonId); } function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return authorised[_owner][_operator]; } function setApprovalForAll(address _operator, bool _approved) external { emit ApprovalForAll(msg.sender,_operator, _approved); authorised[msg.sender][_operator] = _approved; } function tokenURI(uint256 _tokenId) external view isValidToken(_tokenId) returns (string memory) { uint maxlength = 78; bytes memory reversed = new bytes(maxlength); uint i = 0; uint _tmpTokenId = _tokenId; uint _offset = 48; bytes memory _uriBase; _uriBase = bytes(tokenURIPrefix); while (_tmpTokenId != 0) { uint remainder = _tmpTokenId % 10; _tmpTokenId = _tmpTokenId / 10; reversed[i++] = byte(uint8(_offset + remainder)); } bytes memory s = new bytes(_uriBase.length + i); uint j; for (j = 0; j < _uriBase.length; j++) { s[j] = _uriBase[j]; } for (j = 0; j < i; j++) { s[j + _uriBase.length] = reversed[i - 1 - j]; } } function tokenURI(uint256 _tokenId) external view isValidToken(_tokenId) returns (string memory) { uint maxlength = 78; bytes memory reversed = new bytes(maxlength); uint i = 0; uint _tmpTokenId = _tokenId; uint _offset = 48; bytes memory _uriBase; _uriBase = bytes(tokenURIPrefix); while (_tmpTokenId != 0) { uint remainder = _tmpTokenId % 10; _tmpTokenId = _tmpTokenId / 10; reversed[i++] = byte(uint8(_offset + remainder)); } bytes memory s = new bytes(_uriBase.length + i); uint j; for (j = 0; j < _uriBase.length; j++) { s[j] = _uriBase[j]; } for (j = 0; j < i; j++) { s[j + _uriBase.length] = reversed[i - 1 - j]; } } function tokenURI(uint256 _tokenId) external view isValidToken(_tokenId) returns (string memory) { uint maxlength = 78; bytes memory reversed = new bytes(maxlength); uint i = 0; uint _tmpTokenId = _tokenId; uint _offset = 48; bytes memory _uriBase; _uriBase = bytes(tokenURIPrefix); while (_tmpTokenId != 0) { uint remainder = _tmpTokenId % 10; _tmpTokenId = _tmpTokenId / 10; reversed[i++] = byte(uint8(_offset + remainder)); } bytes memory s = new bytes(_uriBase.length + i); uint j; for (j = 0; j < _uriBase.length; j++) { s[j] = _uriBase[j]; } for (j = 0; j < i; j++) { s[j + _uriBase.length] = reversed[i - 1 - j]; } } function tokenURI(uint256 _tokenId) external view isValidToken(_tokenId) returns (string memory) { uint maxlength = 78; bytes memory reversed = new bytes(maxlength); uint i = 0; uint _tmpTokenId = _tokenId; uint _offset = 48; bytes memory _uriBase; _uriBase = bytes(tokenURIPrefix); while (_tmpTokenId != 0) { uint remainder = _tmpTokenId % 10; _tmpTokenId = _tmpTokenId / 10; reversed[i++] = byte(uint8(_offset + remainder)); } bytes memory s = new bytes(_uriBase.length + i); uint j; for (j = 0; j < _uriBase.length; j++) { s[j] = _uriBase[j]; } for (j = 0; j < i; j++) { s[j + _uriBase.length] = reversed[i - 1 - j]; } } return string(s); }
2,699,249
[ 1, 2575, 12279, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 16, 2254, 1578, 9377, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 28425, 265, 2171, 353, 28425, 265, 16541, 16, 28425, 265, 654, 39, 27, 5340, 288, 203, 203, 565, 871, 605, 10542, 12, 2867, 3410, 16, 2254, 5034, 8823, 265, 548, 16, 2254, 5034, 4834, 1949, 548, 16, 2254, 5034, 272, 577, 548, 16, 2254, 5034, 31702, 16, 2254, 1578, 9377, 16, 2254, 1105, 10630, 2355, 1769, 203, 565, 871, 28425, 265, 10726, 7381, 12, 11890, 5034, 389, 15997, 265, 548, 16, 2254, 1105, 389, 2681, 73, 16, 2254, 1105, 389, 346, 1889, 16, 2254, 1105, 389, 334, 13038, 16, 2254, 1105, 389, 474, 1165, 360, 802, 1769, 203, 565, 871, 28425, 265, 6672, 691, 12, 11890, 5034, 389, 15997, 265, 548, 1769, 203, 203, 203, 565, 1958, 28425, 265, 288, 203, 3639, 2254, 5034, 31702, 31, 203, 3639, 2254, 1105, 17057, 950, 31, 203, 3639, 2254, 1105, 324, 15656, 950, 31, 203, 3639, 2254, 1578, 4834, 1949, 548, 31, 203, 3639, 2254, 1578, 272, 577, 548, 31, 203, 3639, 2254, 1578, 272, 11256, 1190, 548, 31, 203, 3639, 2254, 1578, 9377, 31, 203, 565, 289, 203, 203, 565, 1958, 28425, 265, 10726, 288, 203, 3639, 2254, 1105, 10630, 2355, 31, 203, 3639, 2254, 1105, 1737, 1889, 31, 203, 3639, 2254, 1105, 21638, 31, 203, 3639, 2254, 1105, 509, 1165, 360, 802, 31, 203, 565, 289, 203, 203, 565, 28425, 265, 8526, 8823, 7008, 31, 203, 565, 2874, 261, 11890, 5034, 516, 1758, 13, 1071, 8823, 265, 1016, 774, 5541, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 23178, 1345, 1380, 31, 2 ]
pragma solidity ^0.4.23; /* Controls state and access rights for contract functions * @title Operational Control * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) * Inspired and adapted from contract created by OpenZeppelin * Ref: https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract OperationalControl { // Facilitates access & control for the game. // Roles: // -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw) // -The Banker: The Bank can withdraw funds and adjust fees / prices. // -otherManagers: Contracts that need access to functions for gameplay /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public managerPrimary; address public managerSecondary; address public bankManager; // Contracts that require access for gameplay mapping(address => uint8) public otherManagers; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /// @dev Operation modifiers for limiting access modifier onlyManager() { require(msg.sender == managerPrimary || msg.sender == managerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier onlyOtherManagers() { require(otherManagers[msg.sender] == 1); _; } modifier anyOperator() { require( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); _; } /// @dev Assigns a new address to act as the Other Manager. (State = 1 is active, 0 is disabled) function setOtherManager(address _newOp, uint8 _state) external onlyManager { require(_newOp != address(0)); otherManagers[_newOp] = _state; } /// @dev Assigns a new address to act as the Primary Manager. function setPrimaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerPrimary = _newGM; } /// @dev Assigns a new address to act as the Secondary Manager. function setSecondaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerSecondary = _newGM; } /// @dev Assigns a new address to act as the Banker. function setBanker(address _newBK) external onlyManager { require(_newBK != address(0)); bankManager = _newBK; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Modifier to allow actions only when the contract has Error modifier whenError { require(error); _; } /// @dev Called by any Operator role to pause the contract. /// Used only if a bug or exploit is discovered (Here to limit losses / damage) function pause() external onlyManager whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function unpause() public onlyManager whenPaused { // can't unpause if contract was upgraded paused = false; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function hasError() public onlyManager whenPaused { error = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function noError() public onlyManager whenPaused { error = false; } } contract CCNFTFactory { /** Public Functions */ function getAssetDetails(uint256 _assetId) public view returns( uint256 assetId, uint256 ownersIndex, uint256 assetTypeSeqId, uint256 assetType, uint256 createdTimestamp, uint256 isAttached, address creator, address owner ); function getAssetDetailsURI(uint256 _assetId) public view returns( uint256 assetId, uint256 ownersIndex, uint256 assetTypeSeqId, uint256 assetType, uint256 createdTimestamp, uint256 isAttached, address creator, address owner, string metaUriAddress ); function getAssetRawMeta(uint256 _assetId) public view returns( uint256 dataA, uint128 dataB ); function getAssetIdItemType(uint256 _assetId) public view returns( uint256 assetType ); function getAssetIdTypeSequenceId(uint256 _assetId) public view returns( uint256 assetTypeSequenceId ); function getIsNFTAttached( uint256 _tokenId) public view returns( uint256 isAttached ); function getAssetIdCreator(uint256 _assetId) public view returns( address creator ); function getAssetIdOwnerAndOIndex(uint256 _assetId) public view returns( address owner, uint256 ownerIndex ); function getAssetIdOwnerIndex(uint256 _assetId) public view returns( uint256 ownerIndex ); function getAssetIdOwner(uint256 _assetId) public view returns( address owner ); function spawnAsset(address _to, uint256 _assetType, uint256 _assetID, uint256 _isAttached) public; function isAssetIdOwnerOrApproved(address requesterAddress, uint256 _assetId) public view returns( bool ); /// @param _owner The owner whose ships tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire NFT owners array looking for NFT belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens); // Get the name of the Asset type function getTypeName (uint32 _type) public returns(string); function RequestDetachment( uint256 _tokenId ) public; function AttachAsset( uint256 _tokenId ) public; function BatchAttachAssets(uint256[10] _ids) public; function BatchDetachAssets(uint256[10] _ids) public; function RequestDetachmentOnPause (uint256 _tokenId) public; function burnAsset(uint256 _assetID) public; function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received( address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } contract ERC721Holder is ERC721Receiver { function onERC721Received(address, uint256, bytes) public returns(bytes4) { return ERC721_RECEIVED; } } contract CCTimeSaleManager is ERC721Holder, OperationalControl { //DATATYPES & CONSTANTS struct CollectibleSale { // Current owner of NFT (ERC721) address seller; // Price (in wei) at beginning of sale (For Buying) uint256 startingPrice; // Price (in wei) at end of sale (For Buying) uint256 endingPrice; // Duration (in seconds) of sale, 2592000 = 30 days uint256 duration; // Time when sale started // NOTE: 0 if this sale has been concluded uint64 startedAt; // Flag denoting is the Sale still active bool isActive; // address of the wallet who bought the asset address buyer; // ERC721 AssetID uint256 tokenId; } struct PastSales { uint256[5] sales; } // CCNTFAddress address public NFTAddress; // Map from token to their corresponding sale. mapping (uint256 => CollectibleSale) public tokenIdToSale; // Count of AssetType Sales mapping (uint256 => uint256) public assetTypeSaleCount; // Last 5 Prices of AssetType Sales mapping (uint256 => PastSales) internal assetTypeSalePrices; uint256 public avgSalesToCount = 5; // type to sales of type mapping(uint256 => uint256[]) public assetTypeSalesTokenId; event SaleWinner(address owner, uint256 collectibleId, uint256 buyingPrice); event SaleCreated(uint256 tokenID, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint64 startedAt); event SaleCancelled(address seller, uint256 collectibleId); // If > 0 then vending is enable for item type mapping (uint256 => uint256) internal vendingAmountType; // If > 0 then vending is enable for item type mapping (uint256 => uint256) internal vendingTypeSold; // Current Price for vending type mapping (uint256 => uint256) internal vendingPrice; // Price to step up for vending type mapping (uint256 => uint256) internal vendingStepUpAmount; // Qty to step up vending item mapping (uint256 => uint256) internal vendingStepUpQty; uint256 public startingIndex = 100000; uint256 public vendingAttachedState = 1; constructor() public { require(msg.sender != address(0)); paused = true; error = false; managerPrimary = msg.sender; managerSecondary = msg.sender; bankManager = msg.sender; } function setNFTAddress(address _address) public onlyManager { NFTAddress = _address; } function setAvgSalesCount(uint256 _count) public onlyManager { avgSalesToCount = _count; } /// @dev Creates and begins a new sale. function CreateSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint64 _duration, address _seller) public anyOperator { _createSale(_tokenId, _startingPrice, _endingPrice, _duration, _seller); } function BatchCreateSales(uint256[] _tokenIds, uint256 _startingPrice, uint256 _endingPrice, uint64 _duration, address _seller) public anyOperator { uint256 _tokenId; for (uint256 i = 0; i < _tokenIds.length; ++i) { _tokenId = _tokenIds[i]; _createSale(_tokenId, _startingPrice, _endingPrice, _duration, _seller); } } function CreateSaleAvgPrice(uint256 _tokenId, uint256 _margin, uint _minPrice, uint256 _endingPrice, uint64 _duration, address _seller) public anyOperator { var ccNFT = CCNFTFactory(NFTAddress); uint256 assetType = ccNFT.getAssetIdItemType(_tokenId); // Avg Price of last sales uint256 salePrice = GetAssetTypeAverageSalePrice(assetType); // 0-10,000 is mapped to 0%-100% - will be typically 12000 or 120% salePrice = salePrice * _margin / 10000; if(salePrice < _minPrice) { salePrice = _minPrice; } _createSale(_tokenId, salePrice, _endingPrice, _duration, _seller); } function BatchCreateSaleAvgPrice(uint256[] _tokenIds, uint256 _margin, uint _minPrice, uint256 _endingPrice, uint64 _duration, address _seller) public anyOperator { var ccNFT = CCNFTFactory(NFTAddress); uint256 assetType; uint256 _tokenId; uint256 salePrice; for (uint256 i = 0; i < _tokenIds.length; ++i) { _tokenId = _tokenIds[i]; assetType = ccNFT.getAssetIdItemType(_tokenId); // Avg Price of last sales salePrice = GetAssetTypeAverageSalePrice(assetType); // 0-10,000 is mapped to 0%-100% - will be typically 12000 or 120% salePrice = salePrice * _margin / 10000; if(salePrice < _minPrice) { salePrice = _minPrice; } _tokenId = _tokenIds[i]; _createSale(_tokenId, salePrice, _endingPrice, _duration, _seller); } } function BatchCancelSales(uint256[] _tokenIds) public anyOperator { uint256 _tokenId; for (uint256 i = 0; i < _tokenIds.length; ++i) { _tokenId = _tokenIds[i]; _cancelSale(_tokenId); } } function CancelSale(uint256 _assetId) public anyOperator { _cancelSale(_assetId); } function GetCurrentSalePrice(uint256 _assetId) external view returns(uint256 _price) { CollectibleSale memory _sale = tokenIdToSale[_assetId]; return _currentPrice(_sale); } function GetCurrentTypeSalePrice(uint256 _assetType) external view returns(uint256 _price) { CollectibleSale memory _sale = tokenIdToSale[assetTypeSalesTokenId[_assetType][0]]; return _currentPrice(_sale); } function GetCurrentTypeDuration(uint256 _assetType) external view returns(uint256 _duration) { CollectibleSale memory _sale = tokenIdToSale[assetTypeSalesTokenId[_assetType][0]]; return _sale.duration; } function GetCurrentTypeStartTime(uint256 _assetType) external view returns(uint256 _startedAt) { CollectibleSale memory _sale = tokenIdToSale[assetTypeSalesTokenId[_assetType][0]]; return _sale.startedAt; } function GetCurrentTypeSaleItem(uint256 _assetType) external view returns(address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt, uint256 tokenId) { CollectibleSale memory _sale = tokenIdToSale[assetTypeSalesTokenId[_assetType][0]]; return ( _sale.seller, _sale.startingPrice, _sale.endingPrice, _sale.duration, _sale.startedAt, _sale.tokenId ); } function GetCurrentTypeSaleCount(uint256 _assetType) external view returns(uint256 _count) { return assetTypeSalesTokenId[_assetType].length; } function BuyCurrentTypeOfAsset(uint256 _assetType) external whenNotPaused payable { require(msg.sender != address(0)); require(msg.sender != address(this)); CollectibleSale memory _sale = tokenIdToSale[assetTypeSalesTokenId[_assetType][0]]; require(_isOnSale(_sale)); _buy(_sale.tokenId, msg.sender, msg.value); } /// @dev BuyNow Function which call the interncal buy function /// after doing all the pre-checks required to initiate a buy function BuyAsset(uint256 _assetId) external whenNotPaused payable { require(msg.sender != address(0)); require(msg.sender != address(this)); CollectibleSale memory _sale = tokenIdToSale[_assetId]; require(_isOnSale(_sale)); //address seller = _sale.seller; _buy(_assetId, msg.sender, msg.value); } function GetAssetTypeAverageSalePrice(uint256 _assetType) public view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < avgSalesToCount; i++) { sum += assetTypeSalePrices[_assetType].sales[i]; } return sum / 5; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public anyOperator whenPaused { // Actually unpause the contract. super.unpause(); } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT (ERC721) contract, but can be called either by /// the owner or the NFT (ERC721) contract. function withdrawBalance() public onlyBanker { // We are using this boolean method to make sure that even if one fails it will still work bankManager.transfer(address(this).balance); } /// @dev Returns sales info for an CSLCollectibles (ERC721) on sale. /// @param _assetId - ID of the token on sale function getSale(uint256 _assetId) external view returns (address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt, bool isActive, address buyer, uint256 tokenId) { CollectibleSale memory sale = tokenIdToSale[_assetId]; require(_isOnSale(sale)); return ( sale.seller, sale.startingPrice, sale.endingPrice, sale.duration, sale.startedAt, sale.isActive, sale.buyer, sale.tokenId ); } /** Internal Functions */ function _createSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint64 _duration, address _seller) internal { var ccNFT = CCNFTFactory(NFTAddress); require(ccNFT.isAssetIdOwnerOrApproved(this, _tokenId) == true); CollectibleSale memory onSale = tokenIdToSale[_tokenId]; require(onSale.isActive == false); // Sanity check that no inputs overflow how many bits we've allocated // to store them in the sale struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); //Transfer ownership if needed if(ccNFT.ownerOf(_tokenId) != address(this)) { require(ccNFT.isApprovedForAll(msg.sender, this) == true); ccNFT.safeTransferFrom(ccNFT.ownerOf(_tokenId), this, _tokenId); } CollectibleSale memory sale = CollectibleSale( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), true, address(0), uint256(_tokenId) ); _addSale(_tokenId, sale); } /// @dev Adds an sale to the list of open sales. Also fires the /// SaleCreated event. function _addSale(uint256 _assetId, CollectibleSale _sale) internal { // Require that all sales have a duration of // at least one minute. require(_sale.duration >= 1 minutes); tokenIdToSale[_assetId] = _sale; var ccNFT = CCNFTFactory(NFTAddress); uint256 assetType = ccNFT.getAssetIdItemType(_assetId); assetTypeSalesTokenId[assetType].push(_assetId); SaleCreated( uint256(_assetId), uint256(_sale.startingPrice), uint256(_sale.endingPrice), uint256(_sale.duration), uint64(_sale.startedAt) ); } /// @dev Returns current price of a Collectible (ERC721) on sale. Broken into two /// functions (this one, that computes the duration from the sale /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(CollectibleSale memory _sale) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _sale.startedAt) { secondsPassed = now - _sale.startedAt; } return _computeCurrentPrice( _sale.startingPrice, _sale.endingPrice, _sale.duration, secondsPassed ); } /// @dev Computes the current price of an sale. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice(uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addSale()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the sale, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } function _buy(uint256 _assetId, address _buyer, uint256 _price) internal { CollectibleSale storage _sale = tokenIdToSale[_assetId]; // Check that the bid is greater than or equal to the current buyOut price uint256 currentPrice = _currentPrice(_sale); require(_price >= currentPrice); _sale.buyer = _buyer; _sale.isActive = false; _removeSale(_assetId); uint256 bidExcess = _price - currentPrice; _buyer.transfer(bidExcess); var ccNFT = CCNFTFactory(NFTAddress); uint256 assetType = ccNFT.getAssetIdItemType(_assetId); _updateSaleAvgHistory(assetType, _price); ccNFT.safeTransferFrom(this, _buyer, _assetId); emit SaleWinner(_buyer, _assetId, _price); } function _cancelSale (uint256 _assetId) internal { CollectibleSale storage _sale = tokenIdToSale[_assetId]; require(_sale.isActive == true); address sellerAddress = _sale.seller; _removeSale(_assetId); var ccNFT = CCNFTFactory(NFTAddress); ccNFT.safeTransferFrom(this, sellerAddress, _assetId); emit SaleCancelled(sellerAddress, _assetId); } /// @dev Returns true if the FT (ERC721) is on sale. function _isOnSale(CollectibleSale memory _sale) internal view returns (bool) { return (_sale.startedAt > 0 && _sale.isActive); } function _updateSaleAvgHistory(uint256 _assetType, uint256 _price) internal { assetTypeSaleCount[_assetType] += 1; assetTypeSalePrices[_assetType].sales[assetTypeSaleCount[_assetType] % avgSalesToCount] = _price; } /// @dev Removes an sale from the list of open sales. /// @param _assetId - ID of the token on sale function _removeSale(uint256 _assetId) internal { delete tokenIdToSale[_assetId]; var ccNFT = CCNFTFactory(NFTAddress); uint256 assetType = ccNFT.getAssetIdItemType(_assetId); bool hasFound = false; for (uint i = 0; i < assetTypeSalesTokenId[assetType].length; i++) { if ( assetTypeSalesTokenId[assetType][i] == _assetId) { hasFound = true; } if(hasFound == true) { if(i+1 < assetTypeSalesTokenId[assetType].length) assetTypeSalesTokenId[assetType][i] = assetTypeSalesTokenId[assetType][i+1]; else delete assetTypeSalesTokenId[assetType][i]; } } assetTypeSalesTokenId[assetType].length--; } // Vending function setVendingAttachedState (uint256 _collectibleType, uint256 _state) external onlyManager { vendingAttachedState = _state; } /// @dev Function toggle vending for collectible function setVendingAmount (uint256 _collectibleType, uint256 _vendingQty) external onlyManager { vendingAmountType[_collectibleType] = _vendingQty; } /// @dev Function sets the starting price / reset price function setVendingStartPrice (uint256 _collectibleType, uint256 _startingPrice) external onlyManager { vendingPrice[_collectibleType] = _startingPrice; } /// @dev Sets Step Value function setVendingStepValues(uint256 _collectibleType, uint256 _stepAmount, uint256 _stepQty) external onlyManager { vendingStepUpQty[_collectibleType] = _stepQty; vendingStepUpAmount[_collectibleType] = _stepAmount; } /// @dev Create Vending Helper function createVendingItem(uint256 _collectibleType, uint256 _vendingQty, uint256 _startingPrice, uint256 _stepAmount, uint256 _stepQty) external onlyManager { vendingAmountType[_collectibleType] = _vendingQty; vendingPrice[_collectibleType] = _startingPrice; vendingStepUpQty[_collectibleType] = _stepQty; vendingStepUpAmount[_collectibleType] = _stepAmount; } /// @dev This helps in creating a collectible and then /// transfer it _toAddress function vendingCreateCollectible(uint256 _collectibleType, address _toAddress) payable external whenNotPaused { //Only if Vending is Allowed for this Asset require((vendingAmountType[_collectibleType] - vendingTypeSold[_collectibleType]) > 0); require(msg.value >= vendingPrice[_collectibleType]); require(msg.sender != address(0)); require(msg.sender != address(this)); require(_toAddress != address(0)); require(_toAddress != address(this)); var ccNFT = CCNFTFactory(NFTAddress); ccNFT.spawnAsset(_toAddress, _collectibleType, startingIndex, vendingAttachedState); startingIndex += 1; vendingTypeSold[_collectibleType] += 1; uint256 excessBid = msg.value - vendingPrice[_collectibleType]; if(vendingTypeSold[_collectibleType] % vendingStepUpQty[_collectibleType] == 0) { vendingPrice[_collectibleType] += vendingStepUpAmount[_collectibleType]; } if(excessBid > 0) { msg.sender.transfer(excessBid); } } function getVendingAmountLeft (uint256 _collectibleType) view public returns (uint256) { return (vendingAmountType[_collectibleType] - vendingTypeSold[_collectibleType]); } function getVendingAmountSold (uint256 _collectibleType) view public returns (uint256) { return (vendingTypeSold[_collectibleType]); } function getVendingPrice (uint256 _collectibleType) view public returns (uint256) { return (vendingPrice[_collectibleType]); } function getVendingStepPrice (uint256 _collectibleType) view public returns (uint256) { return (vendingStepUpAmount[_collectibleType]); } function getVendingStepQty (uint256 _collectibleType) view public returns (uint256) { return (vendingStepUpQty[_collectibleType]); } function getVendingInfo (uint256 _collectibleType) view public returns (uint256 amountRemaining, uint256 sold, uint256 price, uint256 stepPrice, uint256 stepQty) { amountRemaining = (vendingAmountType[_collectibleType] - vendingTypeSold[_collectibleType]); sold = vendingTypeSold[_collectibleType]; price = vendingPrice[_collectibleType]; stepPrice = vendingStepUpAmount[_collectibleType]; stepQty = vendingStepUpQty[_collectibleType]; } }
Price to step up for vending type
mapping (uint256 => uint256) internal vendingStepUpAmount;
14,742,925
[ 1, 5147, 358, 2235, 731, 364, 331, 2846, 618, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 11890, 5034, 516, 2254, 5034, 13, 2713, 331, 2846, 4160, 1211, 6275, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x2A4f14c7EBece56bef869A402853859388C5B516/sources/contracts/LifeOfGameCreature - autostaking.sol
userData[to].modifiedBlock = uint128(block.number);
function safeMint(uint _darkEnergy, address to) external onlyOwner nonReentrant { uint tokenId = totalSupply.current(); require(tokenId < MAX_CREATURES); totalSupply.increment(); darkEnergy[tokenId] = _darkEnergy; _safeMint(to, tokenId); }
8,328,748
[ 1, 1355, 751, 63, 869, 8009, 7342, 1768, 273, 2254, 10392, 12, 2629, 18, 2696, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 49, 474, 12, 11890, 389, 25045, 664, 31920, 16, 1758, 358, 13, 3903, 1338, 5541, 1661, 426, 8230, 970, 288, 203, 3639, 2254, 1147, 548, 273, 2078, 3088, 1283, 18, 2972, 5621, 203, 3639, 2583, 12, 2316, 548, 411, 4552, 67, 5458, 10511, 55, 1769, 203, 3639, 2078, 3088, 1283, 18, 15016, 5621, 203, 3639, 23433, 664, 31920, 63, 2316, 548, 65, 273, 389, 25045, 664, 31920, 31, 203, 3639, 389, 4626, 49, 474, 12, 869, 16, 1147, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./libraries/Priviledgeable.sol"; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./interfaces/IEmiswap.sol"; import "./interfaces/IEmiVoting.sol"; import "./interfaces/IMooniswap.sol"; import "./libraries/TransferHelper.sol"; import "./libraries/EmiswapLib.sol"; /** * @dev Contract to convert liquidity from other market makers (Uniswap/Mooniswap) to our pairs. */ contract EmiVamp is Initializable, Priviledgeable, ReentrancyGuard { using SafeERC20 for IERC20; struct LPTokenInfo { address lpToken; uint16 tokenType; // Token type: 0 - uniswap (default), 1 - mooniswap } // Info of each third-party lp-token. LPTokenInfo[] public lpTokensInfo; string public codeVersion = "EmiVamp v1.0-183-g3ae9438"; address public ourFactory; event Deposit(address indexed user, address indexed token, uint256 amount); address public defRef; address private _voting; // !!!In updates to contracts set new variables strictly below this line!!! //----------------------------------------------------------------------------------- /** * @dev Implementation of {UpgradeableProxy} type of constructors */ function initialize( address[] memory _lptokens, uint8[] memory _types, address _ourfactory, address _ourvoting ) public initializer { require(_lptokens.length > 0, "EmiVamp: length>0!"); require(_lptokens.length == _types.length, "EmiVamp: lengths!"); require(_ourfactory != address(0), "EmiVamp: factory!"); require(_ourvoting != address(0), "EmiVamp: voting!"); for (uint256 i = 0; i < _lptokens.length; i++) { lpTokensInfo.push( LPTokenInfo({lpToken: _lptokens[i], tokenType: _types[i]}) ); } ourFactory = _ourfactory; _voting = _ourvoting; defRef = address(0xdF3242dE305d033Bb87334169faBBf3b7d3D96c2); _addAdmin(msg.sender); } /** * @dev Returns length of LP-tokens private array */ function lpTokensInfoLength() external view returns (uint256) { return lpTokensInfo.length; } /** * @dev Returns pair base tokens */ function lpTokenDetailedInfo(uint256 _pid) external view returns (address, address) { require(_pid < lpTokensInfo.length, "EmiVamp: Wrong lpToken idx"); if (lpTokensInfo[_pid].tokenType == 0) { // this is uniswap IUniswapV2Pair lpToken = IUniswapV2Pair(lpTokensInfo[_pid].lpToken); return (lpToken.token0(), lpToken.token1()); } else { // this is mooniswap IMooniswap lpToken = IMooniswap(lpTokensInfo[_pid].lpToken); IERC20[] memory t = lpToken.getTokens(); return (address(t[0]), address(t[1])); } } /** * @dev Adds new entry to the list of convertible LP-tokens */ function addLPToken(address _token, uint16 _tokenType) external onlyAdmin returns (uint256) { require(_token != address(0), "EmiVamp: Token address cannot be 0"); require(_tokenType < 2, "EmiVamp: Wrong type"); for (uint256 i = 0; i < lpTokensInfo.length; i++) { if (lpTokensInfo[i].lpToken == _token) { return i; } } lpTokensInfo.push( LPTokenInfo({lpToken: _token, tokenType: _tokenType}) ); return lpTokensInfo.length; } /** * @dev Remove entry from the list of convertible LP-tokens */ function removeLPToken(uint256 _idx) external onlyAdmin { require(_idx < lpTokensInfo.length, "EmiVamp: wrong idx"); delete lpTokensInfo[_idx]; } /** * @dev Change entry from the list of convertible LP-tokens */ function changeLPToken( uint256 _idx, address _token, uint16 _tokenType ) external onlyAdmin { require(_idx < lpTokensInfo.length, "EmiVamp: wrong idx"); require(_token != address(0), "EmiVamp: token=0!"); require(_tokenType < 2, "EmiVamp: wrong tokenType"); lpTokensInfo[_idx].lpToken = _token; lpTokensInfo[_idx].tokenType = _tokenType; } /** * @dev Change emifactory address */ function changeFactory(uint256 _proposalId) external onlyAdmin { address _newFactory; _newFactory = IEmiVoting(_voting).getVotingResult(_proposalId); require( _newFactory != address(0), "EmiVamp: New factory address is wrong" ); ourFactory = _newFactory; } /** * @dev Change default referrer address */ function changeReferral(address _ref) external onlyAdmin { defRef = _ref; } // Deposit LP tokens to us /** * @dev Main function that converts third-party liquidity (represented by LP-tokens) to our own LP-tokens */ function deposit(uint256 _pid, uint256 _amount) public { require(_pid < lpTokensInfo.length, "EmiVamp: pool idx is wrong"); if (lpTokensInfo[_pid].tokenType == 0) { _depositUniswap(_pid, _amount); } else if (lpTokensInfo[_pid].tokenType == 1) { _depositMooniswap(_pid, _amount); } else { return; } emit Deposit(msg.sender, lpTokensInfo[_pid].lpToken, _amount); } /** * @dev Actual function that converts third-party Uniswap liquidity (represented by LP-tokens) to our own LP-tokens */ function _depositUniswap(uint256 _pid, uint256 _amount) internal { IUniswapV2Pair lpToken = IUniswapV2Pair(lpTokensInfo[_pid].lpToken); // check pair existance IERC20 token0 = IERC20(lpToken.token0()); IERC20 token1 = IERC20(lpToken.token1()); // transfer to us TransferHelper.safeTransferFrom( address(lpToken), address(msg.sender), address(lpToken), _amount ); // get liquidity (uint256 amountIn0, uint256 amountIn1) = lpToken.burn(address(this)); _addOurLiquidity( address(token0), address(token1), amountIn0, amountIn1, msg.sender ); } function _addOurLiquidity( address _token0, address _token1, uint256 _amount0, uint256 _amount1, address _to ) internal { (uint256 amountA, uint256 amountB) = _addLiquidity(_token0, _token1, _amount0, _amount1); IEmiswap pairContract = IEmiswapRegistry(ourFactory).pools( IERC20(_token0), IERC20(_token1) ); TransferHelper.safeApprove(_token0, address(pairContract), amountA); TransferHelper.safeApprove(_token1, address(pairContract), amountB); uint256[] memory amounts; amounts = new uint256[](2); uint256[] memory minAmounts; minAmounts = new uint256[](2); if (_token0 < _token1) { amounts[0] = amountA; amounts[1] = amountB; } else { amounts[0] = amountB; amounts[1] = amountA; } uint256 liquidity = IEmiswap(pairContract).deposit(amounts, minAmounts, defRef); TransferHelper.safeTransfer(address(pairContract), _to, liquidity); // return the change if (amountA < _amount0) { // consumed less tokens 0 than given TransferHelper.safeTransfer( _token0, address(msg.sender), _amount0.sub(amountA) ); } if (amountB < _amount1) { // consumed less tokens 1 than given TransferHelper.safeTransfer( _token1, address(msg.sender), _amount1.sub(amountB) ); } } /** * @dev Actual function that converts third-party Mooniswap liquidity (represented by LP-tokens) to our own LP-tokens */ function _depositMooniswap(uint256 _pid, uint256 _amount) internal { IMooniswap lpToken = IMooniswap(lpTokensInfo[_pid].lpToken); IERC20[] memory t = lpToken.getTokens(); // check pair existance IERC20 token0 = IERC20(t[0]); IERC20 token1 = IERC20(t[1]); // transfer to us TransferHelper.safeTransferFrom( address(lpToken), address(msg.sender), address(this), _amount ); uint256 amountBefore0 = token0.balanceOf(address(this)); uint256 amountBefore1 = token1.balanceOf(address(this)); uint256[] memory minVals = new uint256[](2); lpToken.withdraw(_amount, minVals); // get liquidity uint256 amount0 = token0.balanceOf(address(this)).sub(amountBefore0); uint256 amount1 = token1.balanceOf(address(this)).sub(amountBefore1); _addOurLiquidity( address(token0), address(token1), amount0, amount1, msg.sender ); } /** @dev Function check for LP token pair availability. Return _pid or 0 if none exists */ function isPairAvailable(address _token0, address _token1) public view returns (uint16) { require(_token0 != address(0), "EmiVamp: wrong token0 address"); require(_token1 != address(0), "EmiVamp: wrong token1 address"); for (uint16 i = 0; i < lpTokensInfo.length; i++) { address t0 = address(0); address t1 = address(0); if (lpTokensInfo[i].tokenType == 0) { IUniswapV2Pair lpt = IUniswapV2Pair(lpTokensInfo[i].lpToken); t0 = lpt.token0(); t1 = lpt.token1(); } else if (lpTokensInfo[i].tokenType == 1) { IMooniswap lpToken = IMooniswap(lpTokensInfo[i].lpToken); IERC20[] memory t = lpToken.getTokens(); t0 = address(t[0]); t1 = address(t[1]); } else { return 0; } if ( (t0 == _token0 && t1 == _token1) || (t1 == _token0 && t0 == _token1) ) { return 1; } } return 0; } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired ) internal returns (uint256 amountA, uint256 amountB) { IERC20 ERC20tokenA = IERC20(tokenA); IERC20 ERC20tokenB = IERC20(tokenB); IEmiswap pairContract = IEmiswapRegistry(ourFactory).pools(ERC20tokenA, ERC20tokenB); // create the pair if it doesn't exist yet if (pairContract == IEmiswap(0)) { pairContract = IEmiswapRegistry(ourFactory).deploy( ERC20tokenA, ERC20tokenB ); } uint256 reserveA = pairContract.getBalanceForAddition(ERC20tokenA); uint256 reserveB = pairContract.getBalanceForRemoval(ERC20tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint256 amountBOptimal = EmiswapLib.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require( amountBOptimal >= 0, "EmiswapRouter: INSUFFICIENT_B_AMOUNT" ); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint256 amountAOptimal = EmiswapLib.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require( amountAOptimal >= 0, "EmiswapRouter: INSUFFICIENT_A_AMOUNT" ); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } /** * @dev Owner can transfer out any accidentally sent ERC20 tokens */ function transferAnyERC20Token( address tokenAddress, address beneficiary, uint256 tokens ) external onlyAdmin nonReentrant() returns (bool success) { require( tokenAddress != address(0), "EmiVamp: Token address cannot be 0" ); return IERC20(tokenAddress).transfer(beneficiary, tokens); } }
Info of each third-party lp-token.
LPTokenInfo[] public lpTokensInfo;
2,570,784
[ 1, 966, 434, 1517, 12126, 17, 21214, 12423, 17, 2316, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 511, 52, 1345, 966, 8526, 1071, 12423, 5157, 966, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x0021e18f9C37ccE987Dd96A33e3EA4C46D59b088/sources/contracts/Gear.sol
<svg xmlns="http:www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style></style><rect width="100%" height="100%" fill="#fc5c00" /><text x="10" y="20" class="title">Crypto Poker Hand #: '; parts[12] = '</text><text x="10" y="140" class="base"> Legacy: '; parts[13] = getEyeWear(tokenId); parts[14] = '</text><text x="10" y="160" class="base"> Legacy: '; parts[15] = getCyberWare(tokenId); parts[14] = '</text><text x="10" y="200" class="base">Join us at https:justplay.cafe/ to play.</text></svg>';
function tokenURI(uint256 tokenId) override public view returns (string memory) { string[17] memory parts; parts[1] = cards[0]; parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getCardOne(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getCardTwo(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getCardThree(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getCardFour(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getCardFive(tokenId); parts[12] = '</text><text x="10" y="180" class="alert">'; parts[13] = 'You Got <<4 of a Kind>>; Probablilty: <<1 in 2000>>,'; parts[14] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14])); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; }
657,000
[ 1, 32, 11451, 12302, 1546, 2505, 30, 5591, 18, 91, 23, 18, 3341, 19, 17172, 19, 11451, 6, 9420, 17468, 8541, 1546, 92, 2930, 61, 2930, 18721, 6, 1476, 3514, 1546, 20, 374, 890, 3361, 890, 3361, 14050, 4060, 4695, 4060, 4438, 2607, 1835, 1546, 6625, 16407, 2072, 1546, 6625, 16407, 3636, 1546, 7142, 25, 71, 713, 6, 342, 4438, 955, 619, 1546, 2163, 6, 677, 1546, 3462, 6, 667, 1546, 2649, 6441, 18048, 453, 601, 264, 2841, 294, 12386, 2140, 63, 2138, 65, 273, 4357, 955, 4438, 955, 619, 1546, 2163, 6, 677, 1546, 27092, 6, 667, 1546, 1969, 6441, 22781, 30, 12386, 2140, 63, 3437, 65, 273, 4774, 20513, 59, 2091, 12, 2316, 548, 1769, 2140, 63, 3461, 65, 273, 4357, 955, 4438, 955, 619, 1546, 2163, 6, 677, 1546, 16874, 6, 667, 1546, 1969, 6441, 22781, 30, 12386, 2140, 63, 3600, 65, 273, 1927, 93, 744, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 3849, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 533, 63, 4033, 65, 3778, 2140, 31, 203, 3639, 2140, 63, 21, 65, 273, 18122, 63, 20, 15533, 203, 203, 3639, 2140, 63, 22, 65, 273, 4357, 955, 4438, 955, 619, 1546, 2163, 6, 677, 1546, 7132, 6, 667, 1546, 1969, 7918, 31, 203, 203, 3639, 2140, 63, 23, 65, 273, 26776, 3335, 12, 2316, 548, 1769, 203, 203, 3639, 2140, 63, 24, 65, 273, 4357, 955, 4438, 955, 619, 1546, 2163, 6, 677, 1546, 4848, 6, 667, 1546, 1969, 7918, 31, 203, 203, 3639, 2140, 63, 25, 65, 273, 26776, 11710, 12, 2316, 548, 1769, 203, 203, 3639, 2140, 63, 26, 65, 273, 4357, 955, 4438, 955, 619, 1546, 2163, 6, 677, 1546, 3672, 6, 667, 1546, 1969, 7918, 31, 203, 203, 3639, 2140, 63, 27, 65, 273, 26776, 28019, 12, 2316, 548, 1769, 203, 203, 3639, 2140, 63, 28, 65, 273, 4357, 955, 4438, 955, 619, 1546, 2163, 6, 677, 1546, 6625, 6, 667, 1546, 1969, 7918, 31, 203, 203, 3639, 2140, 63, 29, 65, 273, 26776, 42, 477, 12, 2316, 548, 1769, 203, 203, 3639, 2140, 63, 2163, 65, 273, 4357, 955, 4438, 955, 619, 1546, 2163, 6, 677, 1546, 22343, 6, 667, 1546, 1969, 7918, 31, 203, 203, 3639, 2140, 63, 2499, 65, 273, 26776, 42, 688, 12, 2316, 548, 1769, 203, 203, 540, 203, 3639, 2140, 63, 2138, 65, 273, 4357, 955, 4438, 955, 619, 1546, 2163, 6, 2 ]
pragma solidity ^0.4.23; import "./DefaultUserAccount.sol"; contract UserAccountTest { string constant SUCCESS = "success"; string longString = "longString"; string testServiceFunctionSig = "serviceInvocation(address,uint256,bytes32)"; /** * @dev Tests the DefaultUserAccount call forwarding logic */ function testCallForwarding() external returns (string) { uint testState = 42; bytes32 testKey = "myKey"; TestService testService = new TestService(); bool success; DefaultUserAccount account = new DefaultUserAccount(); // The bytes payload encoding the function signature and parameters for the forwarding call bytes memory payload = abi.encodeWithSignature(testServiceFunctionSig, address(this), testState, testKey); // test failures // *IMPORTANT*: the use of the abi.encode function for this call is extremely important since sending the parameters individually via call(bytes4, args...) // has known problems encoding the dynamic-size parameters correctly, see https://github.com/ethereum/solidity/issues/2884 if (address(account).call(bytes4(keccak256("forwardCall(address,bytes)")), abi.encode(address(0), payload))) return "Forwarding a call to an empty address should revert"; (success, ) = account.forwardCall(address(testService), abi.encodeWithSignature("fakeFunction(bytes32)", testState)); if (success) return "Forwarding a call to a non-existent function should return false"; // test successful invocation bytes memory returnData; (success, returnData) = account.forwardCall(address(testService), payload); if (!success) return "Forwarding a call from an authorized address with correct payload should return true"; if (testService.currentEntity() != address(this)) return "The testService should show this address as the current entity"; if (testService.currentState() != testState) return "The testService should have the testState set"; if (testService.currentKey() != testKey) return "The testService should have the testKey set"; if (testService.lastCaller() != address(account)) return "The testService should show the DefaultUserAccount as the last caller"; if (returnData.length != 32) return "ReturnData should be of size 32"; // TODO ability to decode return data via abi requires 0.5.0. // (bytes32 returnMessage) = abi.decode(returnData,(bytes32)); if (toBytes32(returnData, 32) != testService.getSuccessMessage()) return "The function return data should match the service success message"; // test different input/return data payload = abi.encodeWithSignature("isStringLonger5(string)", longString); (success, returnData) = account.forwardCall(address(testService), payload); if (!success) return "isStringLonger5 invocation should succeed"; if (returnData[31] != 1) return "isStringLonger5 should return true for longString"; // boolean is left-padded, so the value is at the end of the bytes payload = abi.encodeWithSignature("getString()"); (success, returnData) = account.forwardCall(address(testService), payload); if (!success) return "getString invocation should succeed"; if (toBytes32(returnData, 32) != 0x20) return "getString should return Hello World at offset 0x20"; if (toBytes32(returnData, 64) != 11) return "getString should return Hello World length"; if (toBytes32(returnData, 96) != "Hello World") return "getString should return Hello World"; return SUCCESS; } function toBytes32(bytes b, int offset) public pure returns (bytes32 result) { assembly { result := mload(add(b, offset)) } } } /** * @dev Contract providing typical service functions to use as target for call forwarding. */ contract TestService { address public currentEntity; uint public currentState; bytes32 public currentKey; address public lastCaller; string public storedString = "Hello World"; function serviceInvocation(address _entity, uint _newState, bytes32 _key) public returns (bytes32) { currentEntity = _entity; currentState = _newState; currentKey = _key; lastCaller = msg.sender; return "congrats"; } function getString() public view returns (string) { return storedString; } function isStringLonger5(string _string) public pure returns (bool) { if (bytes(_string).length > 5) return true; else return false; } function getSuccessMessage() public pure returns (bytes32) { return "congrats"; } }
boolean is left-padded, so the value is at the end of the bytes
if (returnData[31] != 1) return "isStringLonger5 should return true for longString";
7,314,207
[ 1, 6494, 353, 2002, 17, 6982, 785, 16, 1427, 326, 460, 353, 622, 326, 679, 434, 326, 1731, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 202, 430, 261, 2463, 751, 63, 6938, 65, 480, 404, 13, 327, 315, 291, 780, 15927, 693, 25, 1410, 327, 638, 364, 1525, 780, 14432, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/80001/0xcE74e2b2B7f0252273D72dBCf81c6363250F704f/sources/PerformanceCard.sol
.0001 precision. Constant values for creating bonded ERC20 tokens. Reserve Token. Registry Relayed signatures map
contract PerformanceCard is Administrable, ICard, GasPriceLimited { using ECDSA for bytes32; using SafeMath for uint256; using SafeERC20 for IERC20; uint32 public constant MATH_PRECISION = 1e4; IERC20 private reserveToken; IFractionableERC721 private nftRegistry; mapping(bytes => bool) private relayedSignatures; constructor( address _nftRegistry, address _reserveToken ) public { reserveToken = IERC20(_reserveToken); nftRegistry = IFractionableERC721(_nftRegistry); } function executeRelayedTx( uint256 _nonce, address _signer, bytes calldata _abiEncoded, bytes calldata _orderHashSignature ) external returns (bytes memory) { require( relayedSignatures[_orderHashSignature] == false, "PerformanceCard: Invalid _orderSignature" ); bytes32 _hash = keccak256( abi.encodePacked(_nonce, _signer, _abiEncoded) ); require( _signer == _hash.toEthSignedMessageHash().recover(_orderHashSignature), "PerformanceCard: invalid signature verification" ); relayedSignatures[_orderHashSignature] = true; (bool success, bytes memory returndata) = address(this).call( abi.encodePacked(_abiEncoded, _signer) ); if (success) { return returndata; } if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert("PerformanceCard: error in call()"); } } function executeRelayedTx( uint256 _nonce, address _signer, bytes calldata _abiEncoded, bytes calldata _orderHashSignature ) external returns (bytes memory) { require( relayedSignatures[_orderHashSignature] == false, "PerformanceCard: Invalid _orderSignature" ); bytes32 _hash = keccak256( abi.encodePacked(_nonce, _signer, _abiEncoded) ); require( _signer == _hash.toEthSignedMessageHash().recover(_orderHashSignature), "PerformanceCard: invalid signature verification" ); relayedSignatures[_orderHashSignature] = true; (bool success, bytes memory returndata) = address(this).call( abi.encodePacked(_abiEncoded, _signer) ); if (success) { return returndata; } if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert("PerformanceCard: error in call()"); } } function executeRelayedTx( uint256 _nonce, address _signer, bytes calldata _abiEncoded, bytes calldata _orderHashSignature ) external returns (bytes memory) { require( relayedSignatures[_orderHashSignature] == false, "PerformanceCard: Invalid _orderSignature" ); bytes32 _hash = keccak256( abi.encodePacked(_nonce, _signer, _abiEncoded) ); require( _signer == _hash.toEthSignedMessageHash().recover(_orderHashSignature), "PerformanceCard: invalid signature verification" ); relayedSignatures[_orderHashSignature] = true; (bool success, bytes memory returndata) = address(this).call( abi.encodePacked(_abiEncoded, _signer) ); if (success) { return returndata; } if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert("PerformanceCard: error in call()"); } } function executeRelayedTx( uint256 _nonce, address _signer, bytes calldata _abiEncoded, bytes calldata _orderHashSignature ) external returns (bytes memory) { require( relayedSignatures[_orderHashSignature] == false, "PerformanceCard: Invalid _orderSignature" ); bytes32 _hash = keccak256( abi.encodePacked(_nonce, _signer, _abiEncoded) ); require( _signer == _hash.toEthSignedMessageHash().recover(_orderHashSignature), "PerformanceCard: invalid signature verification" ); relayedSignatures[_orderHashSignature] = true; (bool success, bytes memory returndata) = address(this).call( abi.encodePacked(_abiEncoded, _signer) ); if (success) { return returndata; } if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert("PerformanceCard: error in call()"); } } } else { function createCard( uint256 _tokenId, string memory _symbol, string memory _name, uint256 _reserveAmount, bytes32 _msgHash, bytes memory _signature, uint256 _expiration, bytes32 _orderId, bytes memory _orderSignature ) public gasPriceLimited { require( nftRegistry.getBondedERC20(_tokenId) == address(0), "PerformanceCard: card already created" ); bytes32 checkHash = keccak256( abi.encodePacked(_tokenId, _symbol, _name, _reserveAmount) ); require( checkHash == _msgHash, "PerformanceCard: invalid msgHash" ); require( _isValidAdminHash(_msgHash, _signature), "PerformanceCard: invalid admin signature" ); _requireBalance(msgSender(), reserveToken, _reserveAmount); EIP712(address(reserveToken)).transferWithSig( _orderSignature, _reserveAmount, keccak256( abi.encodePacked(_orderId, address(reserveToken), _reserveAmount) ), _expiration, address(this) ); nftRegistry.mintToken(_tokenId, owner(), _symbol, _name); nftRegistry.mintBondedERC20(_tokenId, msgSender(), ERC20_INITIAL_SUPPLY, _reserveAmount); } function swap( uint256 _tokenId, uint256 _amount, uint256 _destTokenId ) public override gasPriceLimited { require( nftRegistry.getBondedERC20(_tokenId) != address(0), "PerformanceCard: tokenId does not exist" ); require( nftRegistry.getBondedERC20(_destTokenId) != address(0), "PerformanceCard: destTokenId does not exist" ); uint256 reserveAmount = nftRegistry.estimateBondedERC20Value( _tokenId, _amount ); uint256 estimatedTokens = nftRegistry.estimateBondedERC20Tokens( _destTokenId, reserveAmount ); nftRegistry.burnBondedERC20(_tokenId, msgSender(), _amount, reserveAmount); nftRegistry.mintBondedERC20(_destTokenId, msgSender(), estimatedTokens, reserveAmount); } function estimateSwap( uint256 _tokenId, uint256 _amount, uint256 _destTokenId ) public view override returns (uint expectedRate, uint slippageRate) { require( nftRegistry.getBondedERC20(_tokenId) != address(0), "PerformanceCard: tokenId does not exist" ); require( nftRegistry.getBondedERC20(_destTokenId) != address(0), "PerformanceCard: destTokenId does not exist" ); uint256 reserveAmount = nftRegistry.estimateBondedERC20Value( _tokenId, _amount ); uint256 estimatedTokens = nftRegistry.estimateBondedERC20Tokens( _destTokenId, reserveAmount ); address bondedToken = nftRegistry.getBondedERC20(_tokenId); expectedRate = estimatedTokens.mul(1e18).div(_amount); slippageRate = reserveAmount.mul(1e18).div( ERC20Manager.poolBalance(bondedToken) ); } function purchase( uint256 _tokenId, uint256 _paymentAmount, uint256 _expiration, bytes32 _orderId, bytes memory _orderSignature ) public override gasPriceLimited { require( nftRegistry.getBondedERC20(_tokenId) != address(0), "PerformanceCard: tokenId does not exist" ); _requireBalance(msgSender(), reserveToken, _paymentAmount); EIP712(address(reserveToken)).transferWithSig( _orderSignature, _paymentAmount, keccak256( abi.encodePacked(_orderId, address(reserveToken), _paymentAmount) ), _expiration, address(this) ); uint256 pFee = _paymentAmount.mul(PLATFORM_CUT).div(MATH_PRECISION); reserveToken.safeTransfer(owner(), pFee); uint256 effectiveReserveAmount = _paymentAmount.sub(pFee); uint256 estimatedTokens = nftRegistry.estimateBondedERC20Tokens( _tokenId, effectiveReserveAmount ); nftRegistry.mintBondedERC20( _tokenId, msgSender(), estimatedTokens, effectiveReserveAmount ); } function estimatePurchase( uint256 _tokenId, uint256 _paymentAmount ) public view override returns (uint expectedRate, uint slippageRate) { require( nftRegistry.getBondedERC20(_tokenId) != address(0), "PerformanceCard: tokenId does not exist" ); uint256 pFees = _paymentAmount.mul(PLATFORM_CUT).div(MATH_PRECISION); uint256 effectiveReserveAmount = _paymentAmount.sub(pFees); uint256 estimatedTokens = nftRegistry.estimateBondedERC20Tokens( _tokenId, effectiveReserveAmount ); address bondedToken = nftRegistry.getBondedERC20(_tokenId); expectedRate = estimatedTokens.mul(1e18).div(_paymentAmount); slippageRate = effectiveReserveAmount.mul(1e18).div( ERC20Manager.poolBalance(bondedToken) ); } function liquidate( uint256 _tokenId, uint256 _liquidationAmount ) public override gasPriceLimited { require( nftRegistry.getBondedERC20(_tokenId) != address(0), "PerformanceCard: tokenId does not exist" ); uint256 reserveAmount = nftRegistry.estimateBondedERC20Value( _tokenId, _liquidationAmount ); nftRegistry.burnBondedERC20( _tokenId, msgSender(), _liquidationAmount, reserveAmount ); reserveToken.safeTransfer(msgSender(), reserveAmount); } function estimateLiquidate( uint256 _tokenId, uint256 _liquidationAmount ) public view override returns (uint expectedRate, uint slippageRate) { require( nftRegistry.getBondedERC20(_tokenId) != address(0), "PerformanceCard: tokenId does not exist" ); address bondedToken = nftRegistry.getBondedERC20(_tokenId); uint256 reserveAmount = nftRegistry.estimateBondedERC20Value( _tokenId, _liquidationAmount ); expectedRate = _liquidationAmount.mul(1e18).div(reserveAmount); slippageRate = reserveAmount.mul(1e18).div( ERC20Manager.poolBalance(bondedToken) ); } function _requireBalance(address _sender, IERC20 _token, uint256 _amount) private view { require( _token.balanceOf(_sender) >= _amount, "PerformanceCard: insufficient balance" ); } function msgSender() private view returns (address payable result) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } return msg.sender; } function msgSender() private view returns (address payable result) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } return msg.sender; } function msgSender() private view returns (address payable result) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } return msg.sender; } }
8,825,419
[ 1, 18, 13304, 6039, 18, 10551, 924, 364, 4979, 324, 265, 785, 4232, 39, 3462, 2430, 18, 1124, 6527, 3155, 18, 5438, 4275, 528, 329, 14862, 852, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 11217, 1359, 6415, 353, 7807, 3337, 429, 16, 467, 6415, 16, 31849, 5147, 3039, 329, 288, 203, 203, 565, 1450, 7773, 19748, 364, 1731, 1578, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 2254, 1578, 1071, 5381, 28394, 67, 3670, 26913, 273, 404, 73, 24, 31, 203, 203, 203, 565, 467, 654, 39, 3462, 3238, 20501, 1345, 31, 203, 203, 565, 11083, 5738, 429, 654, 39, 27, 5340, 3238, 290, 1222, 4243, 31, 203, 203, 565, 2874, 12, 3890, 516, 1426, 13, 3238, 18874, 329, 23918, 31, 203, 203, 377, 3885, 12, 203, 3639, 1758, 389, 82, 1222, 4243, 16, 203, 3639, 1758, 389, 455, 6527, 1345, 203, 565, 262, 203, 3639, 1071, 203, 203, 565, 288, 203, 3639, 20501, 1345, 273, 467, 654, 39, 3462, 24899, 455, 6527, 1345, 1769, 203, 203, 3639, 290, 1222, 4243, 273, 11083, 5738, 429, 654, 39, 27, 5340, 24899, 82, 1222, 4243, 1769, 203, 565, 289, 203, 203, 565, 445, 1836, 27186, 329, 4188, 12, 203, 3639, 2254, 5034, 389, 12824, 16, 203, 3639, 1758, 389, 2977, 264, 16, 203, 3639, 1731, 745, 892, 389, 21457, 10397, 16, 203, 3639, 1731, 745, 892, 389, 1019, 2310, 5374, 203, 565, 262, 203, 3639, 3903, 1135, 261, 3890, 3778, 13, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 18874, 329, 23918, 63, 67, 1019, 2310, 5374, 65, 422, 629, 16, 203, 5411, 315, 25024, 6415, 30, 1962, 389, 1019, 2 ]
./partial_match/5/0x523C34166329f7a2970Be1489379e34D509aD4d8/sources/RewardPool.sol
15 Mar 2021 1615766400
BeginExtract = 1615766400;
16,840,435
[ 1, 3600, 490, 297, 26599, 21, 2872, 3600, 6669, 1105, 713, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 14323, 4976, 273, 2872, 3600, 6669, 1105, 713, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0xaCf247cfFE18E86e53aB497BF9Ad961A4fd017bC/sources/contracts/core/VaultPriceFeed.sol
if _maximise and price is e.g. 1.02, return 1.02 if !_maximise and price is e.g. 0.98, return 0.98
function getPriceV2(address _token, bool _maximise, bool _includeAmmPrice) public view returns (uint256) { uint256 price = getPrimaryPrice(_token, _maximise); if (_includeAmmPrice && isAmmEnabled) { price = getAmmPriceV2(_token, _maximise, price); } if (isSecondaryPriceEnabled) { price = getSecondaryPrice(_token, price, _maximise); } if (strictStableTokens[_token]) { uint256 delta = price > ONE_USD ? price.sub(ONE_USD) : ONE_USD.sub(price); if (delta <= maxStrictPriceDeviation) { return ONE_USD; } if (_maximise && price > ONE_USD) { return price; } if (!_maximise && price < ONE_USD) { return price; } return ONE_USD; } uint256 _spreadBasisPoints = spreadBasisPoints[_token]; if (_maximise) { return price.mul(BASIS_POINTS_DIVISOR.add(_spreadBasisPoints)).div(BASIS_POINTS_DIVISOR); } return price.mul(BASIS_POINTS_DIVISOR.sub(_spreadBasisPoints)).div(BASIS_POINTS_DIVISOR); }
3,749,102
[ 1, 430, 389, 1896, 381, 784, 471, 6205, 353, 425, 18, 75, 18, 404, 18, 3103, 16, 327, 404, 18, 3103, 309, 401, 67, 1896, 381, 784, 471, 6205, 353, 425, 18, 75, 18, 374, 18, 10689, 16, 327, 374, 18, 10689, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 25930, 58, 22, 12, 2867, 389, 2316, 16, 1426, 389, 1896, 381, 784, 16, 1426, 389, 6702, 37, 7020, 5147, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 6205, 273, 11398, 5147, 24899, 2316, 16, 389, 1896, 381, 784, 1769, 203, 203, 3639, 309, 261, 67, 6702, 37, 7020, 5147, 597, 25997, 7020, 1526, 13, 288, 203, 5411, 6205, 273, 4506, 7020, 5147, 58, 22, 24899, 2316, 16, 389, 1896, 381, 784, 16, 6205, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 291, 14893, 5147, 1526, 13, 288, 203, 5411, 6205, 273, 21741, 814, 5147, 24899, 2316, 16, 6205, 16, 389, 1896, 381, 784, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 13948, 30915, 5157, 63, 67, 2316, 5717, 288, 203, 5411, 2254, 5034, 3622, 273, 6205, 405, 15623, 67, 3378, 40, 692, 6205, 18, 1717, 12, 5998, 67, 3378, 40, 13, 294, 15623, 67, 3378, 40, 18, 1717, 12, 8694, 1769, 203, 5411, 309, 261, 9878, 1648, 943, 14809, 5147, 758, 13243, 13, 288, 203, 7734, 327, 15623, 67, 3378, 40, 31, 203, 5411, 289, 203, 203, 5411, 309, 261, 67, 1896, 381, 784, 597, 6205, 405, 15623, 67, 3378, 40, 13, 288, 203, 7734, 327, 6205, 31, 203, 5411, 289, 203, 203, 5411, 309, 16051, 67, 1896, 381, 784, 597, 6205, 411, 15623, 67, 3378, 40, 13, 288, 203, 7734, 327, 6205, 31, 203, 5411, 289, 203, 203, 5411, 327, 15623, 67, 3378, 40, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol"; import "@openzeppelin/contracts/utils/structs/BitMaps.sol"; contract UnboundToken is ERC20, ERC20Permit, ERC20Votes { event Inflate(address _to, uint256 _amount); address public governance; address public pendingGovernance; address public vesting; struct MintParams { address dest; uint256 amount; } modifier onlyGovernance() { require(msg.sender == governance, "not allowed :("); _; } constructor(address _governance) ERC20("Unbound", "UNB") ERC20Permit("Unbound") { governance = _governance; } /// @notice Mint tokens function mint(MintParams[] memory params) external onlyGovernance { for (uint256 i = 0; i < params.length; i++) { _mint(params[i].dest, params[i].amount); } } /// @notice Burn tokens, only vesting contract can burn tokens from vesting /// @param _user Address of the user /// @param _amount Amount of tokens to burn function burn(address _user, uint256 _amount) external { require( msg.sender == vesting || msg.sender == governance, "not allowed" ); _burn(_user, _amount); } /// @notice Remove stuck ERC20's from the contract /// @param _token Address of the token to remove /// @param _to Address to send removed token /// @param _amount Amount of the token function remove( address _token, address _to, uint256 _amount ) external onlyGovernance { IERC20(_token).transfer(_to, _amount); } /// @notice Set address of the vesting, can be done only once /// @param _vesting Address of the vesting contract function setVesting(address _vesting) external onlyGovernance { vesting = _vesting; } /// @notice Change governance /// @param _governance new governance function changeGovernance(address _governance) external onlyGovernance { pendingGovernance = _governance; } /// @notice Accept governance via 2 step process function acceptGovernance() external { require(pendingGovernance == msg.sender); governance = pendingGovernance; pendingGovernance = address(0); } /// @notice Renounces the ownership of the token contract function renounceOwnership() external onlyGovernance { governance = address(0); } // INTERNAL FUNCTIONS // The following functions are overrides required by Solidity. function _afterTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20, ERC20Votes) { super._afterTokenTransfer(from, to, amount); } function _mint(address to, uint256 amount) internal override(ERC20, ERC20Votes) { super._mint(to, amount); } function _burn(address account, uint256 amount) internal override(ERC20, ERC20Votes) { super._burn(account, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/draft-ERC20Permit.sol) pragma solidity ^0.8.0; import "./draft-IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/draft-EIP712.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/Counters.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/ERC20Votes.sol) pragma solidity ^0.8.0; import "./draft-ERC20Permit.sol"; import "../../../utils/math/Math.sol"; import "../../../utils/math/SafeCast.sol"; import "../../../utils/cryptography/ECDSA.sol"; /** * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1. * * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module. * * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * power can be queried through the public accessors {getVotes} and {getPastVotes}. * * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. * Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this * will significantly increase the base gas cost of transfers. * * _Available since v4.2._ */ abstract contract ERC20Votes is ERC20Permit { struct Checkpoint { uint32 fromBlock; uint224 votes; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to an account's voting power. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCast.toUint32(_checkpoints[account].length); } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view virtual returns (address) { return _delegates[account]; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } /** * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. * It is but NOT the sum of all the delegated votes! * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual { _delegate(_msgSender(), delegatee); } /** * @dev Delegates votes from signer to `delegatee` */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); _delegate(signer, delegatee); } /** * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function _maxSupply() internal view virtual returns (uint224) { return type(uint224).max; } /** * @dev Snapshots the totalSupply after it has been increased. */ function _mint(address account, uint256 amount) internal virtual override { super._mint(account, amount); require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); } /** * @dev Snapshots the totalSupply after it has been decreased. */ function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); } /** * @dev Move voting power when tokens are transferred. * * Emits a {DelegateVotesChanged} event. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._afterTokenTransfer(from, to, amount); _moveVotingPower(delegates(from), delegates(to), amount); } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); } function _moveVotingPower( address src, address dst, uint256 amount ) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); } else { ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)})); } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/structs/BitMaps.sol) pragma solidity ^0.8.0; /** * @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential. * Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor]. */ library BitMaps { struct BitMap { mapping(uint256 => uint256) _data; } /** * @dev Returns whether the bit at `index` is set. */ function get(BitMap storage bitmap, uint256 index) internal view returns (bool) { uint256 bucket = index >> 8; uint256 mask = 1 << (index & 0xff); return bitmap._data[bucket] & mask != 0; } /** * @dev Sets the bit at `index` to the boolean `value`. */ function setTo( BitMap storage bitmap, uint256 index, bool value ) internal { if (value) { set(bitmap, index); } else { unset(bitmap, index); } } /** * @dev Sets the bit at `index`. */ function set(BitMap storage bitmap, uint256 index) internal { uint256 bucket = index >> 8; uint256 mask = 1 << (index & 0xff); bitmap._data[bucket] |= mask; } /** * @dev Unsets the bit at `index`. */ function unset(BitMap storage bitmap, uint256 index) internal { uint256 bucket = index >> 8; uint256 mask = 1 << (index & 0xff); bitmap._data[bucket] &= ~mask; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/SafeCast.sol) pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @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 <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(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 <= type(uint64).max, "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 <= type(uint32).max, "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 <= type(uint16).max, "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 <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } }
@notice Mint tokens
function mint(MintParams[] memory params) external onlyGovernance { for (uint256 i = 0; i < params.length; i++) { _mint(params[i].dest, params[i].amount); } }
9,841,984
[ 1, 49, 474, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 49, 474, 1370, 8526, 3778, 859, 13, 3903, 1338, 43, 1643, 82, 1359, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 859, 18, 2469, 31, 277, 27245, 288, 203, 5411, 389, 81, 474, 12, 2010, 63, 77, 8009, 10488, 16, 859, 63, 77, 8009, 8949, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xe37bb96500478285acE5F9F13f9d96dcbB10F263/sources/contracts/MorningsLimitedEditions.flatten.sol
* @notice Mints the next edition of a limited edition NFT @dev Calls internal `_collectEdition` for logic. Reverts if: - the edition requires an off-chain signature - see `_collectEdition` for other conditions @param baseId The base NFT id of the edition @param to The address to mint the token to/
function collectEdition(uint256 baseId, address to) external payable onlyWhenSaleIsLive { TokenData memory tokenData = _baseIdToTokenData[baseId]; if (tokenData.requiresSig) revert RequiresSignature(); _collectEdition(baseId, to, tokenData); }
16,029,749
[ 1, 49, 28142, 326, 1024, 28432, 434, 279, 13594, 28432, 423, 4464, 225, 23665, 2713, 1375, 67, 14676, 41, 1460, 68, 364, 4058, 18, 868, 31537, 309, 30, 225, 300, 326, 28432, 4991, 392, 3397, 17, 5639, 3372, 225, 300, 2621, 1375, 67, 14676, 41, 1460, 68, 364, 1308, 4636, 225, 1026, 548, 1021, 1026, 423, 4464, 612, 434, 326, 28432, 225, 358, 1021, 1758, 358, 312, 474, 326, 1147, 358, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3274, 41, 1460, 12, 11890, 5034, 1026, 548, 16, 1758, 358, 13, 3903, 8843, 429, 1338, 9434, 30746, 2520, 12328, 288, 203, 3639, 3155, 751, 3778, 1147, 751, 273, 389, 1969, 28803, 1345, 751, 63, 1969, 548, 15533, 203, 3639, 309, 261, 2316, 751, 18, 18942, 8267, 13, 15226, 16412, 5374, 5621, 203, 3639, 389, 14676, 41, 1460, 12, 1969, 548, 16, 358, 16, 1147, 751, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xb44FcB65D5E149983EEC12f1f61aed138c1e45d0/sources/contracts/MinterBurner.sol
@notice Mint tokens to '_addr' @param _addr is receiver tokens address @param _amount is amount of tokens
function mintTokens(address _addr, uint256 _amount) external onlyRole(TOKEN_OWNER_ROLE) { require(IGoMiningToken(Token).owner() == address(this), "MinterBurner: not an owner"); IGoMiningToken(Token).mint(_addr, _amount); }
4,933,381
[ 1, 49, 474, 2430, 358, 2070, 4793, 11, 225, 389, 4793, 353, 5971, 2430, 1758, 225, 389, 8949, 353, 3844, 434, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 5157, 12, 2867, 389, 4793, 16, 2254, 5034, 389, 8949, 13, 3903, 1338, 2996, 12, 8412, 67, 29602, 67, 16256, 13, 288, 203, 3639, 2583, 12, 3047, 83, 2930, 310, 1345, 12, 1345, 2934, 8443, 1435, 422, 1758, 12, 2211, 3631, 315, 49, 2761, 38, 321, 264, 30, 486, 392, 3410, 8863, 203, 203, 3639, 467, 5741, 2930, 310, 1345, 12, 1345, 2934, 81, 474, 24899, 4793, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/84531/0xAABeead2Aa1Dc97dbbf44e7daC50e43c50f71DF9/sources/contracts/src/diamond/IDiamond.sol
@notice Execute a diamond cut @param facetAddress Facet to cut. @param action Enum of type FacetCutAction. @param functionSelectors Array of function selectors.
struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; }
16,682,102
[ 1, 5289, 279, 4314, 301, 1434, 6391, 225, 11082, 1887, 31872, 358, 6391, 18, 225, 1301, 6057, 434, 618, 31872, 15812, 1803, 18, 225, 445, 19277, 1510, 434, 445, 11424, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1958, 31872, 15812, 288, 203, 565, 1758, 11082, 1887, 31, 203, 565, 31872, 15812, 1803, 1301, 31, 203, 565, 1731, 24, 8526, 445, 19277, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "./TOSC.sol"; import "./library/SafeMath.sol"; import "./owners.sol"; contract functions is owners{ using SafeMath for uint; TOSC data; constructor(address _TOSCaddress) public { require(_TOSCaddress != address(0)); data = TOSC(_TOSCaddress); } function currentDataAddress() public view returns(address){ return data; } function transfer(address _to, uint256 _value) public{ data.sendTransfer(msg.sender, _to, _value); } function transfer_admin(address _from, address _to, uint256 _value) onlyOwner public{ data.sendTransfer(_from, _to, _value); } function transferToKeeper(address _from, uint256 _value) onlyKeeperOwner public{ data.sendTransfer(_from, keeperOwner, _value); } // 현재 사용안함 // function transferToTestKeeper(address _from, uint256 _value) onlyTestKeeperOwner public{ // address keeperAddress = 0xf65eeD7320D941DA807998a65AFa28a7CA0845e5; // data.sendTransfer(_from, keeperAddress, _value); // } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAddress(address target, bool freeze) onlyOwner public { data.freezeAddress(target, freeze); } function percentLock(address target,uint percentage)onlyOwner public{ require(percentage > 0 && percentage <= 100); uint percent = data.getBalance(target).mul(percentage).mul(100).div(10000); uint avliable = data.getBalance(target).sub(percent); data.PercentLock(target, percentage ,avliable); } function removePercentLock(address target)onlyOwner public{ require(data.getpercentLockedAccount(target) == true); data.removePercentLock(target); } function percentLockCheck(address target) view public returns(string, uint256) { if(data.getpercentLockedAccount(target) == false){ return ("This address is not locked", data.getpercentLockAvailable(target)); }else{ return ("This address is locked ↓↓ Avliable value", data.getpercentLockAvailable(target)); } } function burn(uint256 _value) public { require(data.getBalance(msg.sender) >= _value); // Check if the sender has enough data.burn(msg.sender,_value); } function balanceOf(address addr) public view returns(uint256){ return data.getBalance(addr); } function frozenAdress(address addr) public view returns(bool){ return data.getfrozenAddress(addr); } function recliamOwnership() public onlyOwner { data.transferOwnership(owner); } }
Check if the sender has enough
require(data.getBalance(msg.sender) >= _value);
14,072,649
[ 1, 1564, 309, 326, 5793, 711, 7304, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 892, 18, 588, 13937, 12, 3576, 18, 15330, 13, 1545, 389, 1132, 1769, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../../interfaces/IFlashLoanAddressProvider.sol'; import '../../dependencies/openzeppelin/contracts/IERC20.sol'; import '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import '../../protocol/libraries/types/DataTypes.sol'; import '../../protocol/libraries/helpers/Helpers.sol'; import '../../interfaces/IPriceOracleGetter.sol'; import '../../interfaces/IDepositToken.sol'; import '../../protocol/libraries/configuration/ReserveConfiguration.sol'; import './BaseUniswapAdapter.sol'; /// @notice Liquidation adapter via Uniswap V2 contract FlashLiquidationAdapter is BaseUniswapAdapter { using SafeMath for uint256; using SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; struct LiquidationParams { address collateralAsset; address borrowedAsset; address user; uint256 debtToCover; bool useEthPath; } struct LiquidationCallLocalVars { uint256 initFlashBorrowedBalance; uint256 diffFlashBorrowedBalance; uint256 initCollateralBalance; uint256 diffCollateralBalance; uint256 flashLoanDebt; uint256 soldAmount; uint256 remainingTokens; uint256 borrowedAssetLeftovers; } constructor(IFlashLoanAddressProvider addressesProvider, IUniswapV2Router02ForAdapter uniswapRouter) BaseUniswapAdapter(addressesProvider, uniswapRouter) {} /** * @dev Liquidate a non-healthy position collateral-wise, with a Health Factor below 1, using Flash Loan and Uniswap to repay flash loan premium. * - The caller (liquidator) with a flash loan covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk minus the flash loan premium. * @param assets Address of asset to be swapped * @param amounts Amount of the asset to be swapped * @param premiums Fee of the flash loan * @param initiator Address of the caller * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * address borrowedAsset The asset that must be covered * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); LiquidationParams memory decodedParams = _decodeParams(params); require(assets.length == 1 && assets[0] == decodedParams.borrowedAsset, 'INCONSISTENT_PARAMS'); _liquidateAndSwap( decodedParams.collateralAsset, decodedParams.borrowedAsset, decodedParams.user, decodedParams.debtToCover, decodedParams.useEthPath, amounts[0], premiums[0], initiator ); return true; } /** * @dev * @param collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * @param borrowedAsset The asset that must be covered * @param user The user address with a Health Factor below 1 * @param debtToCover The amount of debt to coverage, can be max(-1) to liquidate all possible debt * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise * @param flashBorrowedAmount Amount of asset requested at the flash loan to liquidate the user position * @param premium Fee of the requested flash loan * @param initiator Address of the caller */ function _liquidateAndSwap( address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath, uint256 flashBorrowedAmount, uint256 premium, address initiator ) internal { LiquidationCallLocalVars memory vars; vars.initCollateralBalance = IERC20(collateralAsset).balanceOf(address(this)); if (collateralAsset != borrowedAsset) { vars.initFlashBorrowedBalance = IERC20(borrowedAsset).balanceOf(address(this)); // Track leftover balance to rescue funds in case of external transfers into this contract vars.borrowedAssetLeftovers = vars.initFlashBorrowedBalance.sub(flashBorrowedAmount); } vars.flashLoanDebt = flashBorrowedAmount.add(premium); // Approve LendingPool to use debt token for liquidation IERC20(borrowedAsset).safeApprove(address(LENDING_POOL), debtToCover); // Liquidate the user position and release the underlying collateral LENDING_POOL.liquidationCall(collateralAsset, borrowedAsset, user, debtToCover, false); // Discover the liquidated tokens uint256 collateralBalanceAfter = IERC20(collateralAsset).balanceOf(address(this)); // Track only collateral released, not current asset balance of the contract vars.diffCollateralBalance = collateralBalanceAfter.sub(vars.initCollateralBalance); if (collateralAsset != borrowedAsset) { // Discover flash loan balance after the liquidation uint256 flashBorrowedAssetAfter = IERC20(borrowedAsset).balanceOf(address(this)); // Use only flash loan borrowed assets, not current asset balance of the contract vars.diffFlashBorrowedBalance = flashBorrowedAssetAfter.sub(vars.borrowedAssetLeftovers); // Swap released collateral into the debt asset, to repay the flash loan vars.soldAmount = _swapTokensForExactTokens( collateralAsset, borrowedAsset, vars.diffCollateralBalance, vars.flashLoanDebt.sub(vars.diffFlashBorrowedBalance), useEthPath ); vars.remainingTokens = vars.diffCollateralBalance.sub(vars.soldAmount); } else { vars.remainingTokens = vars.diffCollateralBalance.sub(premium); } // Allow repay of flash loan // Dont use safeApprove here as there can be leftovers IERC20(borrowedAsset).approve(address(LENDING_POOL), vars.flashLoanDebt); // Transfer remaining tokens to initiator if (vars.remainingTokens > 0) { IERC20(collateralAsset).safeTransfer(initiator, vars.remainingTokens); } } /** * @dev Decodes the information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to claim * address borrowedAsset The asset that must be covered and will be exchanged to pay the flash loan premium * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap * @return LiquidationParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (LiquidationParams memory) { (address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath) = abi.decode( params, (address, address, address, uint256, bool) ); return LiquidationParams(collateralAsset, borrowedAsset, user, debtToCover, useEthPath); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import './IPoolAddressProvider.sol'; interface IFlashLoanAddressProvider is IPoolAddressProvider {} // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; /** * @dev Interface of the ERC20 standard as defined in the EIP excluding events to avoid linearization issues. */ 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. */ 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 */ 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. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import './IERC20.sol'; import './Address.sol'; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; /// @dev Replacement of SafeMath to use with solc 0.8 library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); unchecked { return a - b; } } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; library DataTypes { struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address depositTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the reserve strategy address strategy; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor //bit 80: strategy is external uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} struct InitReserveData { address asset; address depositTokenAddress; address stableDebtAddress; address variableDebtAddress; address strategy; bool externalStrategy; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import '../types/DataTypes.sol'; library Helpers { /// @dev Fetches the user current stable and variable debt balances function getUserCurrentDebt(address user, DataTypes.ReserveData storage reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } function getUserCurrentDebtMemory(address user, DataTypes.ReserveData memory reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; enum SourceType { AggregatorOrStatic, UniswapV2Pair } interface IPriceOracleEvents { event AssetPriceUpdated(address asset, uint256 price, uint256 timestamp); event EthPriceUpdated(uint256 price, uint256 timestamp); event DerivedAssetSourceUpdated( address indexed asset, uint256 index, address indexed underlyingSource, uint256 underlyingPrice, uint256 timestamp, SourceType sourceType ); } /// @dev Interface for a price oracle. interface IPriceOracleGetter is IPriceOracleEvents { /// @dev returns the asset price in ETH function getAssetPrice(address asset) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../dependencies/openzeppelin/contracts/IERC20.sol'; import './IScaledBalanceToken.sol'; import './IPoolToken.sol'; interface IDepositToken is IERC20, IPoolToken, IScaledBalanceToken { /** * @dev Emitted on mint * @param account The receiver of minted tokens * @param value The amount minted * @param index The new liquidity index of the reserve **/ event Mint(address indexed account, uint256 value, uint256 index); /** * @dev Mints `amount` depositTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @param repayOverdraft Enables to use this amount cover an overdraft * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index, bool repayOverdraft ) external returns (bool); /** * @dev Emitted on burn * @param account The owner of tokens burned * @param target The receiver of the underlying * @param value The amount burned * @param index The new liquidity index of the reserve **/ event Burn(address indexed account, address indexed target, uint256 value, uint256 index); /** * @dev Emitted on transfer * @param from The sender * @param to The recipient * @param value The amount transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index); /** * @dev Burns depositTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the depositTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints depositTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers depositTokens in the event of a borrow being liquidated, in case the liquidators reclaims the depositToken * @param from The address getting liquidated, current owner of the depositTokens * @param to The recipient * @param value The amount of tokens getting transferred * @param index The liquidity index of the reserve * @param transferUnderlying is true when the underlying should be, otherwise the depositToken * @return true when transferUnderlying is false and the recipient had zero balance **/ function transferOnLiquidation( address from, address to, uint256 value, uint256 index, bool transferUnderlying ) external returns (bool); /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the underlying * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); function collateralBalanceOf(address) external view returns (uint256); /** * @dev Emitted on use of overdraft (by liquidation) * @param account The receiver of overdraft (user with shortage) * @param value The amount received * @param index The liquidity index of the reserve **/ event OverdraftApplied(address indexed account, uint256 value, uint256 index); /** * @dev Emitted on return of overdraft allowance when it was fully or partially used * @param provider The provider of overdraft * @param recipient The receiver of overdraft * @param overdraft The amount overdraft that was covered by the provider * @param index The liquidity index of the reserve **/ event OverdraftCovered(address indexed provider, address indexed recipient, uint256 overdraft, uint256 index); event SubBalanceProvided(address indexed provider, address indexed recipient, uint256 amount, uint256 index); event SubBalanceReturned(address indexed provider, address indexed recipient, uint256 amount, uint256 index); event SubBalanceLocked(address indexed provider, uint256 amount, uint256 index); event SubBalanceUnlocked(address indexed provider, uint256 amount, uint256 index); function updateTreasury() external; function addSubBalanceOperator(address addr) external; function addStakeOperator(address addr) external; function removeSubBalanceOperator(address addr) external; function provideSubBalance( address provider, address recipient, uint256 scaledAmount ) external; function returnSubBalance( address provider, address recipient, uint256 scaledAmount, bool preferOverdraft ) external returns (uint256 coveredOverdraft); function lockSubBalance(address provider, uint256 scaledAmount) external; function unlockSubBalance( address provider, uint256 scaledAmount, address transferTo ) external; function replaceSubBalance( address prevProvider, address recipient, uint256 prevScaledAmount, address newProvider, uint256 newScaledAmount ) external returns (uint256 coveredOverdraftByPrevProvider); function transferLockedBalance( address from, address to, uint256 scaledAmount ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../../../tools/Errors.sol'; import '../types/DataTypes.sol'; /// @dev ReserveConfiguration library, implements the bitmap logic to handle the reserve configuration library ReserveConfiguration { uint256 private constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore uint256 private constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore uint256 private constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore uint256 private constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore uint256 private constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore uint256 private constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore uint256 private constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore uint256 private constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore uint256 private constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore uint256 private constant STRATEGY_TYPE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFF; // prettier-ignore /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed uint256 private constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16; uint256 private constant LIQUIDATION_BONUS_START_BIT_POSITION = 32; uint256 private constant RESERVE_DECIMALS_START_BIT_POSITION = 48; uint256 private constant RESERVE_FACTOR_START_BIT_POSITION = 64; uint256 private constant MAX_VALID_LTV = 65535; uint256 private constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535; uint256 private constant MAX_VALID_LIQUIDATION_BONUS = 65535; uint256 private constant MAX_VALID_DECIMALS = 255; uint256 private constant MAX_VALID_RESERVE_FACTOR = 65535; /// @dev Sets the Loan to Value of the reserve function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure { require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV); self.data = (self.data & LTV_MASK) | ltv; } /// @dev Gets the Loan to Value of the reserve function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return self.data & ~LTV_MASK; } function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure { require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD); self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION); } function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION; } function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure { require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS); self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION); } function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION; } function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure { require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS); self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION); } function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION; } function getDecimalsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint8) { return uint8((self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION); } function _setFlag( DataTypes.ReserveConfigurationMap memory self, uint256 mask, bool value ) internal pure { if (value) { self.data |= ~mask; } else { self.data &= mask; } } function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure { _setFlag(self, ACTIVE_MASK, active); } function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~ACTIVE_MASK) != 0; } function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure { _setFlag(self, FROZEN_MASK, frozen); } function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~FROZEN_MASK) != 0; } function getFrozenMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) { return (self.data & ~FROZEN_MASK) != 0; } function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure { _setFlag(self, BORROWING_MASK, enabled); } function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~BORROWING_MASK) != 0; } function setStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure { _setFlag(self, STABLE_BORROWING_MASK, enabled); } function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~STABLE_BORROWING_MASK) != 0; } function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure { require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR); self.data = (self.data & RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION); } function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION; } /// @dev Returns flags: active, frozen, borrowing enabled, stableRateBorrowing enabled function getFlags(DataTypes.ReserveConfigurationMap storage self) internal view returns ( bool, bool, bool, bool ) { return _getFlags(self.data); } function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( bool active, bool frozen, bool borrowEnable, bool stableBorrowEnable ) { return _getFlags(self.data); } function _getFlags(uint256 data) private pure returns ( bool, bool, bool, bool ) { return ( (data & ~ACTIVE_MASK) != 0, (data & ~FROZEN_MASK) != 0, (data & ~BORROWING_MASK) != 0, (data & ~STABLE_BORROWING_MASK) != 0 ); } /// @dev Paramters of the reserve: ltv, liquidation threshold, liquidation bonus, the reserve decimals function getParams(DataTypes.ReserveConfigurationMap storage self) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { return _getParams(self.data); } /// @dev Paramters of the reserve: ltv, liquidation threshold, liquidation bonus, the reserve decimals function getParamsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( uint256, uint256, uint256, uint256, uint256 ) { return _getParams(self.data); } function _getParams(uint256 dataLocal) private pure returns ( uint256, uint256, uint256, uint256, uint256 ) { return ( dataLocal & ~LTV_MASK, (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } function isExternalStrategyMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) { return (self.data & ~STRATEGY_TYPE_MASK) != 0; } function isExternalStrategy(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~STRATEGY_TYPE_MASK) != 0; } function setExternalStrategy(DataTypes.ReserveConfigurationMap memory self, bool isExternal) internal pure { _setFlag(self, STRATEGY_TYPE_MASK, isExternal); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../../tools/math/PercentageMath.sol'; import '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import '../../dependencies/openzeppelin/contracts/IERC20.sol'; import '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import '../../interfaces/IFlashLoanAddressProvider.sol'; import '../../protocol/libraries/types/DataTypes.sol'; import '../../interfaces/IPriceOracleGetter.sol'; import '../../tools/tokens/IERC20WithPermit.sol'; import '../../tools/tokens/IERC20Details.sol'; import '../../tools/SweepBase.sol'; import '../../access/AccessFlags.sol'; import '../../access/AccessHelper.sol'; import '../../misc/interfaces/IWETHGateway.sol'; import '../base/FlashLoanReceiverBase.sol'; import './interfaces/IUniswapV2Router02ForAdapter.sol'; import './interfaces/IBaseUniswapAdapter.sol'; // solhint-disable var-name-mixedcase, func-name-mixedcase /// @dev Access to Uniswap V2 abstract contract BaseUniswapAdapter is FlashLoanReceiverBase, SweepBase, IBaseUniswapAdapter { using SafeMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; // Max slippage percent allowed uint256 public immutable override MAX_SLIPPAGE_PERCENT = 3000; // 30% // USD oracle asset address address public constant override USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; address public immutable override WETH_ADDRESS; IUniswapV2Router02ForAdapter public immutable override UNISWAP_ROUTER; constructor(IFlashLoanAddressProvider provider, IUniswapV2Router02ForAdapter uniswapRouter) FlashLoanReceiverBase(provider) { UNISWAP_ROUTER = uniswapRouter; IMarketAccessController ac = IMarketAccessController( ILendingPool(provider.getLendingPool()).getAddressesProvider() ); WETH_ADDRESS = IWETHGateway(ac.getAddress(AccessFlags.WETH_GATEWAY)).getWETHAddress(); } function ORACLE() public view override returns (IPriceOracleGetter) { return IPriceOracleGetter(ADDRESS_PROVIDER.getPriceOracle()); } function getFlashloanPremiumRev() private view returns (uint16) { return uint16(SafeMath.sub(PercentageMath.ONE, LENDING_POOL.getFlashloanPremiumPct(), 'INVALID_FLASHLOAN_PREMIUM')); } function FLASHLOAN_PREMIUM_TOTAL() external view override returns (uint256) { return LENDING_POOL.getFlashloanPremiumPct(); } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsOutData(reserveIn, reserveOut, amountIn); return (results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsInData(reserveIn, reserveOut, amountOut); return (results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path); } /** * @dev Swaps an exact `amountToSwap` of an asset to another * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param amountToSwap Exact amount of `assetToSwapFrom` to be swapped * @param minAmountOut the min amount of `assetToSwapTo` to be received from the swap * @return the amount received from the swap */ function _swapExactTokensForTokens( address assetToSwapFrom, address assetToSwapTo, uint256 amountToSwap, uint256 minAmountOut, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); IPriceOracleGetter oracle = ORACLE(); uint256 fromAssetPrice = oracle.getAssetPrice(assetToSwapFrom); uint256 toAssetPrice = oracle.getAssetPrice(assetToSwapTo); uint256 expectedMinAmountOut = amountToSwap .mul(fromAssetPrice.mul(10**toAssetDecimals)) .div(toAssetPrice.mul(10**fromAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(MAX_SLIPPAGE_PERCENT)); require(expectedMinAmountOut < minAmountOut, 'minAmountOut exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForTokens( amountToSwap, minAmountOut, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[amounts.length - 1]; } /** * @dev Receive an exact amount `amountToReceive` of `assetToSwapTo` tokens for as few `assetToSwapFrom` tokens as * possible. * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param maxAmountToSwap Max amount of `assetToSwapFrom` allowed to be swapped * @param amountToReceive Exact amount of `assetToSwapTo` to receive * @return the amount swapped */ function _swapTokensForExactTokens( address assetToSwapFrom, address assetToSwapTo, uint256 maxAmountToSwap, uint256 amountToReceive, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); IPriceOracleGetter oracle = ORACLE(); uint256 fromAssetPrice = oracle.getAssetPrice(assetToSwapFrom); uint256 toAssetPrice = oracle.getAssetPrice(assetToSwapTo); uint256 expectedMaxAmountToSwap = amountToReceive .mul(toAssetPrice.mul(10**fromAssetDecimals)) .div(fromAssetPrice.mul(10**toAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.add(MAX_SLIPPAGE_PERCENT)); require(maxAmountToSwap < expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), maxAmountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapTokensForExactTokens( amountToReceive, maxAmountToSwap, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[0]; } /** * @dev Get the decimals of an asset * @return number of decimals of the asset */ function _getDecimals(address asset) internal view returns (uint256) { return IERC20Details(asset).decimals(); } /** * @dev Get the depositToken associated to the asset * @return address of the depositToken */ function _getReserveData(address asset) internal view returns (DataTypes.ReserveData memory) { return LENDING_POOL.getReserveData(asset); } /** * @dev Pull the deposit tokens from the user * @param reserve address of the asset * @param depositToken address of the depositToken of the reserve * @param user address * @param amount of tokens to be transferred to the contract * @param permitSignature struct containing the permit signature */ function _pullDepositToken( address reserve, address depositToken, address user, uint256 amount, PermitSignature memory permitSignature ) internal { if (_usePermit(permitSignature)) { IERC20WithPermit(depositToken).permit( user, address(this), permitSignature.amount, permitSignature.deadline, permitSignature.v, permitSignature.r, permitSignature.s ); } // transfer from user to adapter IERC20(depositToken).safeTransferFrom(user, address(this), amount); // withdraw reserve LENDING_POOL.withdraw(reserve, amount, address(this)); } /** * @dev Tells if the permit method should be called by inspecting if there is a valid signature. * If signature params are set to 0, then permit won't be called. * @param signature struct containing the permit signature * @return whether or not permit should be called */ function _usePermit(PermitSignature memory signature) internal pure returns (bool) { return !(uint256(signature.deadline) == uint256(signature.v) && uint256(signature.deadline) == 0); } struct AssetUsdPrice { uint256 ethUsdPrice; uint256 reservePrice; uint256 decimals; } /** * @dev Calculates the value denominated in USD * @param reserve Reserve price params * @param amount Amount of the reserve * @return whether or not permit should be called */ function _calcUsdValue(AssetUsdPrice memory reserve, uint256 amount) internal pure returns (uint256) { return amount.mul(reserve.reservePrice).div(10**reserve.decimals).mul(reserve.ethUsdPrice).div(10**18); } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountIn Amount of reserveIn * @return Struct containing the following information: * uint256 Amount out of the reserveOut * uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsOutData( address reserveIn, address reserveOut, uint256 amountIn ) internal view returns (AmountCalc memory) { // Deduct flash loan fee uint256 finalAmountIn = amountIn.percentMul(getFlashloanPremiumRev()); IPriceOracleGetter oracle = ORACLE(); AssetUsdPrice memory reserveInPrice = AssetUsdPrice( oracle.getAssetPrice(USD_ADDRESS), oracle.getAssetPrice(reserveIn), _getDecimals(reserveIn) ); AssetUsdPrice memory reserveOutPrice; if (reserveIn == reserveOut) { reserveOutPrice = reserveInPrice; address[] memory path = new address[](1); path[0] = reserveIn; return AmountCalc( finalAmountIn, finalAmountIn.mul(10**18).div(amountIn), _calcUsdValue(reserveInPrice, amountIn), _calcUsdValue(reserveInPrice, finalAmountIn), path ); } else { reserveOutPrice = AssetUsdPrice( reserveInPrice.ethUsdPrice, oracle.getAssetPrice(reserveOut), _getDecimals(reserveOut) ); } address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, pathWithWeth) returns (uint256[] memory resultsWithWeth) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } uint256 bestAmountOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, simplePath) returns (uint256[] memory resultAmounts) { amountsWithoutWeth = resultAmounts; bestAmountOut = (amountsWithWeth[2] > amountsWithoutWeth[1]) ? amountsWithWeth[2] : amountsWithoutWeth[1]; } catch { amountsWithoutWeth = new uint256[](2); bestAmountOut = amountsWithWeth[2]; } uint256 outPerInPrice = finalAmountIn.mul(10**18).mul(10**reserveOutPrice.decimals).div( bestAmountOut.mul(10**reserveInPrice.decimals) ); return AmountCalc( bestAmountOut, outPerInPrice, _calcUsdValue(reserveInPrice, amountIn), _calcUsdValue(reserveOutPrice, bestAmountOut), (bestAmountOut == 0) ? new address[](2) : (bestAmountOut == amountsWithoutWeth[1]) ? simplePath : pathWithWeth ); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return Struct containing the following information: * uint256 Amount in of the reserveIn * uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsInData( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (AmountCalc memory) { IPriceOracleGetter oracle = ORACLE(); AssetUsdPrice memory reserveInPrice = AssetUsdPrice( oracle.getAssetPrice(USD_ADDRESS), oracle.getAssetPrice(reserveIn), _getDecimals(reserveIn) ); AssetUsdPrice memory reserveOutPrice; uint16 flashloanPremiumRev = getFlashloanPremiumRev(); if (reserveIn == reserveOut) { reserveOutPrice = reserveInPrice; // Add flash loan fee uint256 amountIn = amountOut.percentDiv(flashloanPremiumRev); address[] memory path_ = new address[](1); path_[0] = reserveIn; return AmountCalc( amountIn, amountOut.mul(10**18).div(amountIn), _calcUsdValue(reserveInPrice, amountIn), _calcUsdValue(reserveInPrice, amountOut), path_ ); } else { reserveOutPrice = AssetUsdPrice( reserveInPrice.ethUsdPrice, oracle.getAssetPrice(reserveOut), _getDecimals(reserveOut) ); } (uint256[] memory amounts, address[] memory path) = _getAmountsInAndPath(reserveIn, reserveOut, amountOut); // Add flash loan fee uint256 finalAmountIn = amounts[0].percentDiv(flashloanPremiumRev); uint256 inPerOutPrice = amountOut.mul(10**18).mul(10**reserveInPrice.decimals).div( finalAmountIn.mul(10**reserveOutPrice.decimals) ); return AmountCalc( finalAmountIn, inPerOutPrice, _calcUsdValue(reserveInPrice, finalAmountIn), _calcUsdValue(reserveOutPrice, amountOut), path ); } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsInAndPath( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (uint256[] memory, address[] memory) { address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsIn(amountOut, pathWithWeth) returns (uint256[] memory resultsWithWeth) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } try UNISWAP_ROUTER.getAmountsIn(amountOut, simplePath) returns (uint256[] memory resultAmounts) { amountsWithoutWeth = resultAmounts; return (amountsWithWeth[0] < amountsWithoutWeth[0] && amountsWithWeth[0] != 0) ? (amountsWithWeth, pathWithWeth) : (amountsWithoutWeth, simplePath); } catch { return (amountsWithWeth, pathWithWeth); } } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsIn( address reserveIn, address reserveOut, uint256 amountOut, bool useEthPath ) internal view returns (uint256[] memory) { address[] memory path; if (useEthPath) { path = new address[](3); path[0] = reserveIn; path[1] = WETH_ADDRESS; path[2] = reserveOut; } else { path = new address[](2); path[0] = reserveIn; path[1] = reserveOut; } return UNISWAP_ROUTER.getAmountsIn(amountOut, path); } function _onlySweepAdmin() internal view override { IMarketAccessController ac = IMarketAccessController(LENDING_POOL.getAddressesProvider()); AccessHelper.requireAnyOf(ac, msg.sender, AccessFlags.SWEEP_ADMIN, Errors.CALLER_NOT_SWEEP_ADMIN); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import './IPriceOracleProvider.sol'; interface IPoolAddressProvider is IPriceOracleProvider { function getLendingPool() external view returns (address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; interface IPriceOracleProvider { function getPriceOracle() external view returns (address); function getLendingRateOracle() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; // solhint-disable no-inline-assembly, avoid-low-level-calls /** * @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; } bytes32 private constant accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; function isExternallyOwned(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; uint256 size; assembly { codehash := extcodehash(account) size := extcodesize(account) } return codehash == accountHash && 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}. */ 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. * * 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: agpl-3.0 pragma solidity ^0.8.4; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); function getScaleIndex() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import './IDerivedToken.sol'; // solhint-disable func-name-mixedcase interface IPoolToken is IDerivedToken { function POOL() external view returns (address); function updatePool() external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; // solhint-disable func-name-mixedcase interface IDerivedToken { /** * @dev Returns the address of the underlying asset of this token (E.g. WETH for agWETH) **/ function UNDERLYING_ASSET_ADDRESS() external view returns (address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; /** * @title Errors library * @notice Defines the error messages emitted by the different contracts * @dev Error messages prefix glossary: * - VL = ValidationLogic * - MATH = Math libraries * - CT = Common errors between tokens (DepositToken, VariableDebtToken and StableDebtToken) * - AT = DepositToken * - SDT = StableDebtToken * - VDT = VariableDebtToken * - LP = LendingPool * - LPAPR = AddressesProviderRegistry * - LPC = LendingPoolConfiguration * - RL = ReserveLogic * - LPCM = LendingPoolExtension * - ST = Stake */ library Errors { //contract specific errors string public constant VL_INVALID_AMOUNT = '1'; // Amount must be greater than 0 string public constant VL_NO_ACTIVE_RESERVE = '2'; // Action requires an active reserve string public constant VL_RESERVE_FROZEN = '3'; // Action cannot be performed because the reserve is frozen string public constant VL_UNKNOWN_RESERVE = '4'; // Action requires an active reserve string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // User cannot withdraw more than the available balance (above min limit) string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // Transfer cannot be allowed. string public constant VL_BORROWING_NOT_ENABLED = '7'; // Borrowing is not enabled string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // Invalid interest rate mode selected string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // The collateral balance is 0 string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // Health factor is lesser than the liquidation threshold string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // There is not enough collateral to cover a new borrow string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // The requested amount is exceeds max size of a stable loan string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // to repay a debt, user needs to specify a correct debt type (variable or stable) string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // To repay on behalf of an user an explicit amount to repay is needed string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // User does not have a stable rate loan in progress on this reserve string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // User does not have a variable rate loan in progress on this reserve string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // The collateral balance needs to be greater than 0 string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // User deposit is already being used as collateral string public constant VL_RESERVE_MUST_BE_COLLATERAL = '21'; // This reserve must be enabled as collateral string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // Interest rate rebalance conditions were not met string public constant AT_OVERDRAFT_DISABLED = '23'; // User doesn't accept allocation of overdraft string public constant VL_INVALID_SUB_BALANCE_ARGS = '24'; string public constant AT_INVALID_SLASH_DESTINATION = '25'; string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // The caller of the function is not the lending pool configurator string public constant LENDING_POOL_REQUIRED = '28'; // The caller of this function must be a lending pool string public constant CALLER_NOT_LENDING_POOL = '29'; // The caller of this function must be a lending pool string public constant AT_SUB_BALANCE_RESTIRCTED_FUNCTION = '30'; // The caller of this function must be a lending pool or a sub-balance operator string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // Reserve has already been initialized string public constant CALLER_NOT_POOL_ADMIN = '33'; // The caller must be the pool admin string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // The liquidity of the reserve needs to be 0 string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // Provider is not registered string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // Health factor is not below the threshold string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // The collateral chosen cannot be liquidated string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // User did not borrow the specified currency string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // There isn't enough liquidity available to liquidate string public constant MATH_MULTIPLICATION_OVERFLOW = '48'; string public constant MATH_ADDITION_OVERFLOW = '49'; string public constant MATH_DIVISION_BY_ZERO = '50'; string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128 string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128 string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint string public constant CALLER_NOT_STAKE_ADMIN = '57'; string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small string public constant CALLER_NOT_LIQUIDITY_CONTROLLER = '60'; string public constant CALLER_NOT_REF_ADMIN = '61'; string public constant VL_INSUFFICIENT_REWARD_AVAILABLE = '62'; string public constant LP_CALLER_MUST_BE_DEPOSIT_TOKEN = '63'; string public constant LP_IS_PAUSED = '64'; // Pool is paused string public constant LP_NO_MORE_RESERVES_ALLOWED = '65'; string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; string public constant RC_INVALID_LTV = '67'; string public constant RC_INVALID_LIQ_THRESHOLD = '68'; string public constant RC_INVALID_LIQ_BONUS = '69'; string public constant RC_INVALID_DECIMALS = '70'; string public constant RC_INVALID_RESERVE_FACTOR = '71'; string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; string public constant VL_TREASURY_REQUIRED = '74'; string public constant LPC_INVALID_CONFIGURATION = '75'; // Invalid risk parameters for the reserve string public constant CALLER_NOT_EMERGENCY_ADMIN = '76'; // The caller must be the emergency admin string public constant UL_INVALID_INDEX = '77'; string public constant VL_CONTRACT_REQUIRED = '78'; string public constant SDT_STABLE_DEBT_OVERFLOW = '79'; string public constant SDT_BURN_EXCEEDS_BALANCE = '80'; string public constant CALLER_NOT_REWARD_CONFIG_ADMIN = '81'; // The caller of this function must be a reward admin string public constant LP_INVALID_PERCENTAGE = '82'; // Percentage can't be more than 100% string public constant LP_IS_NOT_TRUSTED_FLASHLOAN = '83'; string public constant CALLER_NOT_SWEEP_ADMIN = '84'; string public constant LP_TOO_MANY_NESTED_CALLS = '85'; string public constant LP_RESTRICTED_FEATURE = '86'; string public constant LP_TOO_MANY_FLASHLOAN_CALLS = '87'; string public constant RW_BASELINE_EXCEEDED = '88'; string public constant CALLER_NOT_REWARD_RATE_ADMIN = '89'; string public constant CALLER_NOT_REWARD_CONTROLLER = '90'; string public constant RW_REWARD_PAUSED = '91'; string public constant CALLER_NOT_TEAM_MANAGER = '92'; string public constant STK_REDEEM_PAUSED = '93'; string public constant STK_INSUFFICIENT_COOLDOWN = '94'; string public constant STK_UNSTAKE_WINDOW_FINISHED = '95'; string public constant STK_INVALID_BALANCE_ON_COOLDOWN = '96'; string public constant STK_EXCESSIVE_SLASH_PCT = '97'; string public constant STK_WRONG_COOLDOWN_OR_UNSTAKE = '98'; string public constant STK_PAUSED = '99'; string public constant TXT_OWNABLE_CALLER_NOT_OWNER = 'Ownable: caller is not the owner'; string public constant TXT_CALLER_NOT_PROXY_OWNER = 'ProxyOwner: caller is not the owner'; string public constant TXT_ACCESS_RESTRICTED = 'RESTRICTED'; } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../Errors.sol'; /// @dev Percentages are defined in basis points. The precision is indicated by ONE. Operations are rounded half up. library PercentageMath { uint16 public constant BP = 1; // basis point uint16 public constant PCT = 100 * BP; // basis points per percentage point uint16 public constant ONE = 100 * PCT; // basis points per 1 (100%) uint16 public constant HALF_ONE = ONE / 2; // deprecated uint256 public constant PERCENTAGE_FACTOR = ONE; //percentage plus two decimals /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param factor Basis points of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 factor) internal pure returns (uint256) { if (value == 0 || factor == 0) { return 0; } require(value <= (type(uint256).max - HALF_ONE) / factor, Errors.MATH_MULTIPLICATION_OVERFLOW); return (value * factor + HALF_ONE) / ONE; } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param factor Basis points of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 factor) internal pure returns (uint256) { require(factor != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfFactor = factor >> 1; require(value <= (type(uint256).max - halfFactor) / ONE, Errors.MATH_MULTIPLICATION_OVERFLOW); return (value * ONE + halfFactor) / factor; } function percentOf(uint256 value, uint256 base) internal pure returns (uint256) { require(base != 0, Errors.MATH_DIVISION_BY_ZERO); if (value == 0) { return 0; } require(value <= (type(uint256).max - HALF_ONE) / ONE, Errors.MATH_MULTIPLICATION_OVERFLOW); return (value * ONE + (base >> 1)) / base; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../../dependencies/openzeppelin/contracts/IERC20.sol'; interface IERC20WithPermit is IERC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; interface IERC20Details { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../dependencies/openzeppelin/contracts/Address.sol'; import '../dependencies/openzeppelin/contracts/IERC20.sol'; import '../dependencies/openzeppelin/contracts/SafeERC20.sol'; import '../interfaces/ISweeper.sol'; import './Errors.sol'; abstract contract SweepBase is ISweeper { address private constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; function sweepToken( address token, address to, uint256 amount ) external override { _onlySweepAdmin(); if (token == ETH) { Address.sendValue(payable(to), amount); } else { SafeERC20.safeTransfer(IERC20(token), to, amount); } } function _onlySweepAdmin() internal view virtual; } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; library AccessFlags { // roles that can be assigned to multiple addresses - use range [0..15] uint256 public constant EMERGENCY_ADMIN = 1 << 0; uint256 public constant POOL_ADMIN = 1 << 1; uint256 public constant TREASURY_ADMIN = 1 << 2; uint256 public constant REWARD_CONFIG_ADMIN = 1 << 3; uint256 public constant REWARD_RATE_ADMIN = 1 << 4; uint256 public constant STAKE_ADMIN = 1 << 5; uint256 public constant REFERRAL_ADMIN = 1 << 6; uint256 public constant LENDING_RATE_ADMIN = 1 << 7; uint256 public constant SWEEP_ADMIN = 1 << 8; uint256 public constant ORACLE_ADMIN = 1 << 9; uint256 public constant ROLES = (uint256(1) << 16) - 1; // singletons - use range [16..64] - can ONLY be assigned to a single address uint256 public constant SINGLETONS = ((uint256(1) << 64) - 1) & ~ROLES; // proxied singletons uint256 public constant LENDING_POOL = 1 << 16; uint256 public constant LENDING_POOL_CONFIGURATOR = 1 << 17; uint256 public constant LIQUIDITY_CONTROLLER = 1 << 18; uint256 public constant TREASURY = 1 << 19; uint256 public constant REWARD_TOKEN = 1 << 20; uint256 public constant REWARD_STAKE_TOKEN = 1 << 21; uint256 public constant REWARD_CONTROLLER = 1 << 22; uint256 public constant REWARD_CONFIGURATOR = 1 << 23; uint256 public constant STAKE_CONFIGURATOR = 1 << 24; uint256 public constant REFERRAL_REGISTRY = 1 << 25; uint256 public constant PROXIES = ((uint256(1) << 26) - 1) & ~ROLES; // non-proxied singletons, numbered down from 31 (as JS has problems with bitmasks over 31 bits) uint256 public constant WETH_GATEWAY = 1 << 27; uint256 public constant DATA_HELPER = 1 << 28; uint256 public constant PRICE_ORACLE = 1 << 29; uint256 public constant LENDING_RATE_ORACLE = 1 << 30; // any other roles - use range [64..] // these roles can be assigned to multiple addresses uint256 public constant TRUSTED_FLASHLOAN = 1 << 66; } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import './interfaces/IRemoteAccessBitmask.sol'; /// @dev Helper/wrapper around IRemoteAccessBitmask library AccessHelper { function getAcl(IRemoteAccessBitmask remote, address subject) internal view returns (uint256) { return remote.queryAccessControlMask(subject, ~uint256(0)); } function queryAcl( IRemoteAccessBitmask remote, address subject, uint256 filterMask ) internal view returns (uint256) { return remote.queryAccessControlMask(subject, filterMask); } function hasAnyOf( IRemoteAccessBitmask remote, address subject, uint256 flags ) internal view returns (bool) { uint256 found = queryAcl(remote, subject, flags); return found & flags != 0; } function hasAny(IRemoteAccessBitmask remote, address subject) internal view returns (bool) { return remote.queryAccessControlMask(subject, 0) != 0; } function hasNone(IRemoteAccessBitmask remote, address subject) internal view returns (bool) { return remote.queryAccessControlMask(subject, 0) == 0; } function requireAnyOf( IRemoteAccessBitmask remote, address subject, uint256 flags, string memory text ) internal view { require(hasAnyOf(remote, subject, flags), text); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; interface IWETHGateway { function depositETH( address lendingPool, address onBehalfOf, uint256 referralCode ) external payable; function withdrawETH( address lendingPool, uint256 amount, address onBehalfOf ) external; function repayETH( address lendingPool, uint256 amount, uint256 rateMode, address onBehalfOf ) external payable; function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint256 referralCode ) external; function getWETHAddress() external view returns (address); } interface IWETHGatewayCompatible { function depositETH( address lendingPool, address onBehalfOf, uint16 referralCode ) external payable; function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint16 referralCode ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../interfaces/IFlashLoanReceiver.sol'; import '../../interfaces/IFlashLoanAddressProvider.sol'; import '../../interfaces/ILendingPool.sol'; // solhint-disable var-name-mixedcase, func-name-mixedcase abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { IFlashLoanAddressProvider public immutable override ADDRESS_PROVIDER; ILendingPool public immutable override LENDING_POOL; constructor(IFlashLoanAddressProvider provider) { ADDRESS_PROVIDER = provider; LENDING_POOL = ILendingPool(provider.getLendingPool()); } /// @dev backward compatibility function ADDRESSES_PROVIDER() external view returns (IFlashLoanAddressProvider) { return ADDRESS_PROVIDER; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; /// @dev Defines a minimal subset of functions used by Uniswap adapters interface IUniswapV2Router02ForAdapter { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../../../interfaces/IPriceOracleGetter.sol'; import './IUniswapV2Router02ForAdapter.sol'; // solhint-disable func-name-mixedcase interface IBaseUniswapAdapter { event Swapped(address fromAsset, address toAsset, uint256 fromAmount, uint256 receivedAmount); struct PermitSignature { uint256 amount; uint256 deadline; uint8 v; bytes32 r; bytes32 s; } struct AmountCalc { uint256 calculatedAmount; uint256 relativePrice; uint256 amountInUsd; uint256 amountOutUsd; address[] path; } function WETH_ADDRESS() external view returns (address); function MAX_SLIPPAGE_PERCENT() external view returns (uint256); function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint256); function USD_ADDRESS() external view returns (address); function ORACLE() external view returns (IPriceOracleGetter); function UNISWAP_ROUTER() external view returns (IUniswapV2Router02ForAdapter); /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; interface ISweeper { /// @dev transfer ERC20 from the utility contract, for ERC20 recovery of direct transfers to the contract address. function sweepToken( address token, address to, uint256 amount ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; interface IRemoteAccessBitmask { /** * @dev Returns access flags granted to the given address and limited by the filterMask. filterMask == 0 has a special meaning. * @param addr an to get access perfmissions for * @param filterMask limits a subset of flags to be checked. * NB! When filterMask == 0 then zero is returned no flags granted, or an unspecified non-zero value otherwise. * @return Access flags currently granted */ function queryAccessControlMask(address addr, uint256 filterMask) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../../interfaces/IFlashLoanAddressProvider.sol'; import '../../interfaces/ILendingPool.sol'; // solhint-disable func-name-mixedcase /** * @title IFlashLoanReceiver interface * @notice Interface for the Aave fee IFlashLoanReceiver. * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external returns (bool); function ADDRESS_PROVIDER() external view returns (IFlashLoanAddressProvider); function LENDING_POOL() external view returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../protocol/libraries/types/DataTypes.sol'; import './ILendingPoolEvents.sol'; interface ILendingPool is ILendingPoolEvents { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying depositTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the depositTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of depositTokens * is a different wallet * @param referral Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint256 referral ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent depositTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole depositToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referral Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint256 referral, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveDeposit `true` if the liquidators wants to receive the collateral depositTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveDeposit ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referral Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint256 referral ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (address); function getFlashloanPremiumPct() external view returns (uint16); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../access/interfaces/IMarketAccessController.sol'; import '../protocol/libraries/types/DataTypes.sol'; interface ILendingPoolEvents { /// @dev Emitted on deposit() event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 indexed referral ); /// @dev Emitted on withdraw() event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /// @dev Emitted on borrow() and flashLoan() when debt needs to be opened event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint256 indexed referral ); /// @dev Emitted on repay() event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /// @dev Emitted on swapBorrowRateMode() event Swap(address indexed reserve, address indexed user, uint256 rateMode); /// @dev Emitted on setUserUseReserveAsCollateral() event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /// @dev Emitted on setUserUseReserveAsCollateral() event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /// @dev Emitted on rebalanceStableBorrowRate() event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /// @dev Emitted on flashLoan() event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint256 referral ); /// @dev Emitted when a borrower is liquidated. event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveDeposit ); /// @dev Emitted when the state of a reserve is updated. event ReserveDataUpdated( address indexed underlying, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); event LendingPoolExtensionUpdated(address extension); event DisabledFeaturesUpdated(uint16 disabledFeatures); event FlashLoanPremiumUpdated(uint16 premium); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import './IAccessController.sol'; /// @dev Main registry of addresses part of or connected to the protocol, including permissioned roles. Also acts a proxy factory. interface IMarketAccessController is IAccessController { function getMarketId() external view returns (string memory); function getLendingPool() external view returns (address); function getPriceOracle() external view returns (address); function getLendingRateOracle() external view returns (address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import './IRemoteAccessBitmask.sol'; import '../../tools/upgradeability/IProxy.sol'; /// @dev Main registry of permissions and addresses interface IAccessController is IRemoteAccessBitmask { function getAddress(uint256 id) external view returns (address); function createProxy( address admin, address impl, bytes calldata params ) external returns (IProxy); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; interface IProxy { function upgradeToAndCall(address newImplementation, bytes calldata data) external payable; }
@dev ReserveConfiguration library, implements the bitmap logic to handle the reserve configuration
library ReserveConfiguration { uint256 private constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16; uint256 private constant LIQUIDATION_BONUS_START_BIT_POSITION = 32; uint256 private constant RESERVE_DECIMALS_START_BIT_POSITION = 48; uint256 private constant RESERVE_FACTOR_START_BIT_POSITION = 64; uint256 private constant MAX_VALID_LTV = 65535; uint256 private constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535; uint256 private constant MAX_VALID_LIQUIDATION_BONUS = 65535; uint256 private constant MAX_VALID_DECIMALS = 255; uint256 private constant MAX_VALID_RESERVE_FACTOR = 65535; } pragma solidity ^0.8.4; function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure { require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV); self.data = (self.data & LTV_MASK) | ltv; } function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return self.data & ~LTV_MASK; } function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure { require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD); self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION); } function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION; } function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure { require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS); self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION); } function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION; } function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure { require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS); self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION); } function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION; } function getDecimalsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint8) { return uint8((self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION); } function _setFlag( DataTypes.ReserveConfigurationMap memory self, uint256 mask, bool value ) internal pure { if (value) { self.data |= ~mask; self.data &= mask; } } function _setFlag( DataTypes.ReserveConfigurationMap memory self, uint256 mask, bool value ) internal pure { if (value) { self.data |= ~mask; self.data &= mask; } } } else { function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure { _setFlag(self, ACTIVE_MASK, active); } function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~ACTIVE_MASK) != 0; } function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure { _setFlag(self, FROZEN_MASK, frozen); } function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~FROZEN_MASK) != 0; } function getFrozenMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) { return (self.data & ~FROZEN_MASK) != 0; } function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure { _setFlag(self, BORROWING_MASK, enabled); } function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~BORROWING_MASK) != 0; } function setStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure { _setFlag(self, STABLE_BORROWING_MASK, enabled); } function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~STABLE_BORROWING_MASK) != 0; } function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure { require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR); self.data = (self.data & RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION); } function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION; } function getFlags(DataTypes.ReserveConfigurationMap storage self) internal view returns ( bool, bool, bool, bool ) { return _getFlags(self.data); } function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( bool active, bool frozen, bool borrowEnable, bool stableBorrowEnable ) { return _getFlags(self.data); } function _getFlags(uint256 data) private pure returns ( bool, bool, bool, bool ) { return ( (data & ~ACTIVE_MASK) != 0, (data & ~FROZEN_MASK) != 0, (data & ~BORROWING_MASK) != 0, (data & ~STABLE_BORROWING_MASK) != 0 ); } function getParams(DataTypes.ReserveConfigurationMap storage self) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { return _getParams(self.data); } function getParamsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( uint256, uint256, uint256, uint256, uint256 ) { return _getParams(self.data); } function _getParams(uint256 dataLocal) private pure returns ( uint256, uint256, uint256, uint256, uint256 ) { return ( dataLocal & ~LTV_MASK, (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } function isExternalStrategyMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) { return (self.data & ~STRATEGY_TYPE_MASK) != 0; } function isExternalStrategy(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~STRATEGY_TYPE_MASK) != 0; } function setExternalStrategy(DataTypes.ReserveConfigurationMap memory self, bool isExternal) internal pure { _setFlag(self, STRATEGY_TYPE_MASK, isExternal); } }
11,914,242
[ 1, 607, 6527, 1750, 5313, 16, 4792, 326, 9389, 4058, 358, 1640, 326, 20501, 1664, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 1124, 6527, 1750, 288, 203, 203, 225, 2254, 5034, 3238, 5381, 8961, 53, 3060, 2689, 67, 23840, 67, 7570, 67, 15650, 67, 15258, 273, 2872, 31, 203, 225, 2254, 5034, 3238, 5381, 8961, 53, 3060, 2689, 67, 38, 673, 3378, 67, 7570, 67, 15650, 67, 15258, 273, 3847, 31, 203, 225, 2254, 5034, 3238, 5381, 2438, 2123, 3412, 67, 23816, 55, 67, 7570, 67, 15650, 67, 15258, 273, 9934, 31, 203, 225, 2254, 5034, 3238, 5381, 2438, 2123, 3412, 67, 26835, 67, 7570, 67, 15650, 67, 15258, 273, 5178, 31, 203, 203, 225, 2254, 5034, 3238, 5381, 4552, 67, 5063, 67, 12050, 58, 273, 10147, 31, 203, 225, 2254, 5034, 3238, 5381, 4552, 67, 5063, 67, 2053, 53, 3060, 2689, 67, 23840, 273, 10147, 31, 203, 225, 2254, 5034, 3238, 5381, 4552, 67, 5063, 67, 2053, 53, 3060, 2689, 67, 38, 673, 3378, 273, 10147, 31, 203, 225, 2254, 5034, 3238, 5381, 4552, 67, 5063, 67, 23816, 55, 273, 4561, 31, 203, 225, 2254, 5034, 3238, 5381, 4552, 67, 5063, 67, 862, 2123, 3412, 67, 26835, 273, 10147, 31, 203, 203, 97, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 225, 445, 444, 48, 24161, 12, 751, 2016, 18, 607, 6527, 1750, 863, 3778, 365, 16, 2254, 5034, 13489, 90, 13, 2713, 16618, 288, 203, 565, 2583, 12, 5618, 90, 1648, 4552, 67, 5063, 67, 12050, 58, 16, 9372, 18, 11529, 67, 9347, 67, 12050, 58, 1769, 203, 203, 565, 365, 18, 892, 273, 261, 2890, 18, 892, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-05-14 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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 This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it * return `block.number` will trigger the creation of snapshot at the begining of each new block. When overridding this * function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract. * * Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient * alternative consider {ERC20Votes}. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it * return `block.number` will trigger the creation of snapshot at the begining of each new block. When overridding this * function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract. * * Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient * alternative consider {ERC20Votes}. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _getCurrentSnapshotId(); emit Snapshot(currentId); return currentId; } /** * @dev Get the current snapshotId */ function _getCurrentSnapshotId() internal view virtual returns (uint256) { return _currentSnapshotId.current(); } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view virtual returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // mint _updateAccountSnapshot(to); _updateTotalSupplySnapshot(); } else if (to == address(0)) { // burn _updateAccountSnapshot(from); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(from); _updateAccountSnapshot(to); } } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); require(snapshotId <= _getCurrentSnapshotId(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _getCurrentSnapshotId(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } /** * @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); } } /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } /** * @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;` */ 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; } } } // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } contract Swan is ERC20Snapshot, Ownable { using SafeMath for uint256; uint256 public constant burnRate = 10; uint256 public constant bonusRate = 10; address public crossTokenAddress; address public governanceAddress; address public bonusAddress; constructor() ERC20("Swan Swap", "SWAN") { _mint(msg.sender, 90000000000000000); crossTokenAddress = msg.sender; governanceAddress = msg.sender; bonusAddress = msg.sender; } function _transfer(address sender, address recipient, uint256 amount) internal virtual override { uint256 burnAmount = amount.mul(burnRate).div(10000); uint256 bonusAmount = amount.mul(bonusRate).div(10000); uint256 transferAmount = amount.sub(burnAmount).sub(bonusAmount); _burn(sender, burnAmount); super._transfer(sender, bonusAddress, bonusAmount); super._transfer(sender, recipient, transferAmount); } function burn(uint256 amount) public { _burn(msg.sender, amount); } function burnFrom(address account, uint256 amount) public { uint256 currentAllowance = allowance(account, msg.sender); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, msg.sender, currentAllowance - amount); _burn(account, amount); } function snapshot() public onlyOwner returns (uint256) { return _snapshot(); } function crossSwap(uint256 amount) public { require(msg.sender == crossTokenAddress, "FORBIDDEN"); require(msg.sender != owner(), "FORBIDDEN"); _mint(msg.sender, amount); } function crossBurn(address account, uint256 amount) public { require(msg.sender == crossTokenAddress, "FORBIDDEN"); require(msg.sender != owner(), "FORBIDDEN"); _burn(account, amount); } function decimals() public view virtual override returns (uint8) { return 0; } function setCrossTokenAddress(address _crossTokenAddress) public { require(msg.sender == crossTokenAddress, "FORBIDDEN"); crossTokenAddress = _crossTokenAddress; } function setGovernanceAddress(address _governanceAddress) public { require(msg.sender == governanceAddress, "FORBIDDEN"); governanceAddress = _governanceAddress; } function setBonusTokenAddress(address _bonusAddress) public { require(msg.sender == bonusAddress, "FORBIDDEN"); bonusAddress = _bonusAddress; } }
* @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. By default, the owner account will be the one that deploys the contract. This can later be changed with {transferOwnership}. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner./
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } }
2,037,962
[ 1, 8924, 1605, 1492, 8121, 279, 5337, 2006, 3325, 12860, 16, 1625, 1915, 353, 392, 2236, 261, 304, 3410, 13, 716, 848, 506, 17578, 12060, 2006, 358, 2923, 4186, 18, 2525, 805, 16, 326, 3410, 2236, 903, 506, 326, 1245, 716, 5993, 383, 1900, 326, 6835, 18, 1220, 848, 5137, 506, 3550, 598, 288, 13866, 5460, 12565, 5496, 1220, 1605, 353, 1399, 3059, 16334, 18, 2597, 903, 1221, 2319, 326, 9606, 1375, 3700, 5541, 9191, 1492, 848, 506, 6754, 358, 3433, 4186, 358, 13108, 3675, 999, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 14223, 6914, 353, 1772, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 565, 3885, 1832, 288, 203, 3639, 1758, 1234, 12021, 273, 389, 3576, 12021, 5621, 203, 3639, 389, 8443, 273, 1234, 12021, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 1234, 12021, 1769, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 8443, 1435, 422, 389, 3576, 12021, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 3639, 389, 8443, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.22 <0.6.0; pragma experimental ABIEncoderV2; import "./RoleManager.sol"; import "./TokenManager.sol"; //This contracts handles the trip logic and acts as a platform contract owning the TokenManager contract and the RoleManager contract contract PlatformContract { offer[] tripArray; //each trip offer by a lessor is stored in this array uint256[] indexOfID; //0 means offer got deleted RoleManager roleManager; //roleManager contract associated to this platform contract TokenManager tokenManager; //tokenManager contract associated to this platform contract mapping (address => user) public usermap; //can rent or subrent objects //Verifier Section //calling neccessary modifiers to implement the trip logic from the subclass //Every role issue not directly related to trips is exclusively handeled in the subclass modifier onlyVerifiedRenter(uint8 objectType) { require (roleManager.isVerifiedRenter(msg.sender, objectType) == true); _; } //objectType descirbes the sharing object category (car, charging station, bike, ...) modifier onlyVerifiedLessor(uint8 objectType) { require (roleManager.isVerifiedLessor(msg.sender, objectType) == true); _; } modifier onlyVerifiers() { require (roleManager.isVerifier(msg.sender) == true); _; } //renters who fail to pay for a trip have limited action right on the paltform modifier onlyWithoutDebt() { require (tokenManager.hasDebt(msg.sender) == 0); _; } modifier onlyAuthorities() { require (roleManager.isAuthority(msg.sender) == true); _; } //renters or lessors which violated laws or acted in a malicious way can be blocked by authorities modifier isNotBlockedRenter() { require (roleManager.isBlocked(msg.sender, false) == false); _; } modifier isNotBlockedLessor() { require (roleManager.isBlocked(msg.sender, true) == false); _; } //Each offer issued by a verified lessor needs to provide the following attributes struct offer //offer cant be reserved while its started { address lessor; //lessor of the rental object uint256 startTime; //start time in sconds since uint epoch (01.January 1970) -> use DateTime contract to convert Date to timestampt uint256 endTime; //end time in sconds since uint epoch (01.January 1970) -> use DateTime contract to convert Date to timestampt uint64 latpickupLocation; //lattitude of rental object pcikup location uint64 longpickupLocation; //longitude of rental object pcikup location uint64[10] latPolygons; uint64[10] longPolygons; // at most 10 lattitude and longitude points to define return area of rental object address renter; //renter of the object bool reserved; //Is a trip reserved? uint256 reservedBlockNumber; //BlockNumber when a trip got reserved uint256 maxReservedAmount; //max amount of reservation time allowed in blocknumbers bool readyToUse; //Lessor needs to state if the device is ready for use (unlockable, ...) so that the renter does not need to pay for waiting //bool locked; //user might want to lock the object (car,..) during a trip to unlock it later (maybe not needed to be handled on chain but rather by interacting with the device itself) uint256 started; //Block number of start time, 0 by default -> acts as a bool check uint256 userDemandsEnd; //Block number of end demand uint256 id; //Uid of the trip uint256 price; //price in tokens per block (5 secs) uint8 objectType; //car, charging station, ... string model; //further information like BMW i3, Emmy Vesper, can be also used to present a more accurate picture to the user in the app } //users can be lessors or renters struct user { bool reserved; //did the user reserve a trip? -> maybe increase to a limit of multiple trips(?) bool started; //did the user start a trip? uint256 rating; //Review Rating for that user from 1-5 on Client side -> possible future feature that lessors can also rate renters and trips may automatically reject low rated renters uint256 ratingCount; //how often has this user been rated? Used to calculate rating mapping(address => bool) hasRatingRight; //checks if user has the right to give a 1-5 star rating for a trip lessor (1 right for each ended trip) mapping(address => bool) hasReportRight; //checks if the user has the right to give a report for a trip lessor } //description: how do you want to name the first token? constructor(string memory description) public { roleManager = new RoleManager(msg.sender); //creating a new instance of a subcontract in the parent class //Initializes first authority when contract is created tokenManager = new TokenManager(); tokenManager.createNewToken(msg.sender,description); //Genesis Token/ First Token offer memory temp; //Genesis offer, cant be booked tripArray.push(temp); indexOfID.push(0); //0 id, indicates that trip got deleted, never used for an existing trip, points to Genesis trip } //authorities who want to interact with the On Chain Governance need the address of the created local instance of the RoleManager contract function getRoleManagerAddress() public view returns(address) { return address(roleManager); } function getTokemManagerAddress() public view returns(address) { return address(tokenManager); } //after an authority is voted in it has the right to create at most one token for itself function createNewToken(string memory description) public onlyAuthorities { tokenManager.createNewToken(msg.sender, description); } //ReservationSection //Checks if object can be reservated by anyone right now, true is it can get reservated function getIsReservable(uint256 id) public view returns (bool) { if(tripArray[indexOfID[id]].reserved == false) //Even when the users status gets changed from reserved to started after starting a trip, the trip status actually is reserved and started at the same time return true; if(block.number - tripArray[indexOfID[id]].reservedBlockNumber > tripArray[indexOfID[id]].maxReservedAmount && tripArray[indexOfID[id]].started == 0) //if a trip exceeds the maxReservedAmount but was not started yet it can be reserved by another party again return true; return false; } //Object needs to be free, user needs to be verifired and cant have other reservations function reserveTrip(uint256 id) public onlyVerifiedRenter( tripArray[indexOfID[id]].objectType) onlyWithoutDebt isNotBlockedRenter { require(usermap[msg.sender].reserved == false); //***************else: emit already reserved Trip event*************** require(getIsReservable(id) == true); //***************else: emit already reserved by somone else event *************** // require(usermap[msg.sender].balance > 1000); //require minimum balance *************change ERC20***************** require(tokenManager.getTotalBalanceOfUser(msg.sender) > 50*tripArray[indexOfID[id]].price); //with 5secs blocktime around 4 mins worth of balance usermap[msg.sender].reserved = true; tripArray[indexOfID[id]].reserved = true; tripArray[indexOfID[id]].renter = msg.sender; tripArray[indexOfID[id]].reservedBlockNumber = block.number; //reservation gets timstampt as its validity is time limited //***************emit Reservation successful event*************** // tokenManager.blockOtherPaymentsOfUser(msg.sender, tripArray[indexOfID[id]].lessor); //give allowance instead? } //canceling trip is only possible if user reserved the trip but did not start it yet function cancelReserve(uint256 id) public { if(tripArray[indexOfID[id]].renter == msg.sender && tripArray[indexOfID[id]].started == 0) { tripArray[indexOfID[id]].reserved = false; usermap[msg.sender].reserved = false; //***************emit Reservation cancel successful event*************** // tokenManager.unblockOtherPaymentsOfUser(msg.sender); } //***************emit Reservation cancel not successful event*************** } //start and end Trip section //users can only start trips if they are not blocked, dont have any debt, have a minimum balancethreshold right now, have not started another trip yet, have given the tokenManager contract allowance to deduct tokens on their behalf function startTrip(uint256 id) public onlyWithoutDebt isNotBlockedRenter { require(tripArray[indexOfID[id]].renter == msg.sender && tripArray[indexOfID[id]].started == 0); require(usermap[msg.sender].started == false); //user can only have 1 started trip // require(usermap[msg.sender].balance > 1000); //require minimum balance *************change ERC20***************** require(tokenManager.getTotalBalanceOfUser(msg.sender) > 50*tripArray[indexOfID[id]].price); //user should have atleast enough balance for 50*5seconds -> around 4mins, minimum trip length require(tokenManager.getHasTotalAllowance(msg.sender) == true); //emit tripStart(tripAddress, tripKey, msg.sender, block.number); tokenManager.blockOtherPaymentsOfUser(msg.sender, tripArray[indexOfID[id]].lessor); //user gets blocked to make transactions to other addresses tripArray[indexOfID[id]].readyToUse = false; //setting unlocked to false to esnure rental object is ready to use before user is charged tripArray[indexOfID[id]].started = block.number; usermap[msg.sender].started = true; usermap[msg.sender].hasReportRight[tripArray[indexOfID[id]].lessor] = true; //renter gets the right to submit a report if something is wrong at the start or during the trip (e.g. object not found, object not functioning properly, lessor maliciously rejected end of trip), reports always have to be accompanied by off chain prove client side and will be reviewed by authorites (or possibly additional roles) } //Authority needs to confirm after start trip that device is ready to used (unlocked,...) function confirmReadyToUse(uint256 id) public { require(tripArray[indexOfID[id]].lessor == msg.sender); tripArray[indexOfID[id]].started = block.number; //update started so user does not pay for waiting time tripArray[indexOfID[id]].readyToUse = true; //emit unlocked event } //only callable by Renter, demanding End of trip has to be confrimed by the lessor (valid drop off location,...) function demandEndTrip(uint256 id) public { require(tripArray[indexOfID[id]].renter == msg.sender && tripArray[indexOfID[id]].started != 0); require(usermap[msg.sender].started == true); //safety check, shouldnt be neccessarry to check require(tripArray[indexOfID[id]].userDemandsEnd == 0); tripArray[indexOfID[id]].userDemandsEnd = block.number; } //only callable by Renter, if lessor does not respond within 15 seconds, the renter can force end the trip function userForcesEndTrip(uint256 id) public { require(tripArray[indexOfID[id]].renter == msg.sender && tripArray[indexOfID[id]].started != 0); require(usermap[msg.sender].started == true); //safety check, shouldnt be neccessarry to check require(block.number > tripArray[indexOfID[id]].userDemandsEnd+3); //authority has 3 blocks time to answer to endDemand request contractEndsTrip(id); } //only callable by lessor if user wants to end the trip, confirms that the pbject was returned adequatly function confirmEndTrip(uint256 id) public { require(tripArray[indexOfID[id]].lessor == msg.sender && tripArray[indexOfID[id]].started != 0); require(tripArray[indexOfID[id]].userDemandsEnd != 0); contractEndsTrip(id); } //only callable by lessor if user wants to end the trip, states that the pbject was returned inadequatly, rejects endTrip attempt of renter, renter can always report against malicious use of this function function rejectEndTrip(uint256 id) public { require(tripArray[indexOfID[id]].lessor == msg.sender && tripArray[indexOfID[id]].started != 0); require(tripArray[indexOfID[id]].userDemandsEnd != 0); tripArray[indexOfID[id]].userDemandsEnd = 0; tripArray[indexOfID[id]].userDemandsEnd = 0; //probably best to add an event and parse a string reason in parameters to state and explain why trip end was rejected } //On long rentals Lessor can call this function to ensure sufficient balance from the user -> maybe dont use that function, just tell the user and add debt -> good idea for charging station as renter can force end easily here function doubtBalanceEnd(uint256 id) public { require(tripArray[indexOfID[id]].lessor == msg.sender && tripArray[indexOfID[id]].started != 0); //**************ERC20*********** if balance is not sufficient, renter can end contract require(tripArray[indexOfID[id]].objectType == 4); //assuming object type 4 means charging station, function only makes sense for charging station require(tokenManager.getTotalBalanceOfUser(msg.sender) > 10*tripArray[indexOfID[id]].price); //if user has less than 50seconds worth of balance then the Lessor can forceEnd the trip to prevent failure of payment contractEndsTrip(id); //Alternative: automatically end trips after certain amount and require user to rebook trips } //if renter demands end of trip and forces it or lessor confirms, the PlatformContract calls this function to handle payment and set all trip and user states to the right value again function contractEndsTrip (uint256 id) internal { //*****************************ERC20Payment, out of money(?)************************************** if(tripArray[indexOfID[id]].readyToUse) //user only needs to pay if the device actually responded and is ready to use -> maybe take out for testing to not require vehicle response all the time { if( tripArray[indexOfID[id]].userDemandsEnd == 0) //in this case user has to pay the difference form the current block number, should only happen if trip was force ended by authority tokenManager.handlePayment(block.number - tripArray[indexOfID[id]].started,tripArray[indexOfID[id]].price, msg.sender, tripArray[indexOfID[id]].lessor); //handle payment with elapsed time,´price of trip, from and to address else //in this case user only has to be the time until he/she demanded end of trip (user does not have to pay for the time it takes the rental object authority to confirm the trip) tokenManager.handlePayment(tripArray[indexOfID[id]].userDemandsEnd - tripArray[indexOfID[id]].started,tripArray[indexOfID[id]].price, msg.sender, tripArray[indexOfID[id]].lessor); //handle payment with elapsed time,´price of trip, from and to address } if(tokenManager.hasDebt(msg.sender) == 0) tokenManager.unblockOtherPaymentsOfUser(msg.sender); //only unblocks user if the user managed to pay the full amount usermap[msg.sender].started = false; usermap[msg.sender].hasRatingRight[tripArray[indexOfID[id]].lessor] = true; //address def; tripArray[indexOfID[id]].renter = address(0); //-> prob adress(0) tripArray[indexOfID[id]].reserved = false; tripArray[indexOfID[id]].started = 0; tripArray[indexOfID[id]].userDemandsEnd = 0; tripArray[indexOfID[id]].readyToUse = false; //restrict user from access to the vehicle => needs to be replicated in device logic } //returns the maxiumum amount of blocks the user can still rent the device before he/she runs out of balance, useful for client side warnings function getMaxRamainingTime(uint256 id) public view returns (uint256) { require(tripArray[indexOfID[id]].started != 0); uint256 currentPrice = (block.number - tripArray[indexOfID[id]].started)*tripArray[indexOfID[id]].price; uint256 userBalance = tokenManager.getTotalBalanceOfUser(tripArray[indexOfID[id]].renter); uint256 theoreticalBalanceLeft = currentPrice -userBalance; return theoreticalBalanceLeft/tripArray[indexOfID[id]].price; } //User has a rating right for each ended trip function rateTrip(address LessorAddress, uint8 rating) public { require(usermap[msg.sender].hasRatingRight[LessorAddress] == true); require(rating > 0); require(rating < 6); usermap[LessorAddress].rating += rating; usermap[LessorAddress].ratingCount++; usermap[msg.sender].hasRatingRight[LessorAddress] = false; } //User has the right to report a lessor for each started trip (might be useful to also add one for each reserved trip but allows spamming) function reportLessor(address LessorAddress, uint8 rating, string memory message) public { require(usermap[msg.sender].hasReportRight[LessorAddress] == true); //****here reports could be stored in an array with an own report governance logic or emited as an event for offchain handling by auhtorities which then return for on chain punishment**** usermap[msg.sender].hasReportRight[LessorAddress] = false; } //Offer trip section //use DateTime contract before to convert desired Date to uint epoch function offerTrip(uint256 startTime, uint256 endTime, uint64 latpickupLocation, uint64 longpickupLocation, uint256 price, uint64[10] memory latPolygons, uint64[10] memory longPolygons, uint256 maxReservedAmount, uint8 objectType, string memory model ) public onlyVerifiedLessor(objectType) isNotBlockedLessor { offer memory tempOffer; tempOffer.startTime = startTime; tempOffer.endTime = endTime; tempOffer.latpickupLocation = latpickupLocation; tempOffer.longpickupLocation = longpickupLocation; tempOffer.lessor = msg.sender; tempOffer.price = price; tempOffer.latPolygons = latPolygons; tempOffer.longPolygons = longPolygons; tempOffer.maxReservedAmount = maxReservedAmount; tempOffer.objectType = objectType; tempOffer.model = model; tempOffer.id = indexOfID.length; // set id to the next following tripArray.push(tempOffer); //add trip to the tripArray indexOfID.push(tripArray.length-1); //save location for latest id -> is linked to tempOffer.id from before } //Change Trip details Section //lessors can update object location if not in use or reserved function updateObjectLocation(uint256 id, uint64 newlat, uint64 newlong) public onlyVerifiedLessor(tripArray[indexOfID[id]].objectType) //modifier might not be neccessary { require(tripArray[indexOfID[id]].lessor == msg.sender); require(tripArray[indexOfID[id]].reserved == false); tripArray[indexOfID[id]].longpickupLocation = newlong; tripArray[indexOfID[id]].latpickupLocation = newlat; } //lessors can update object price if not in use or reserved function updateObjectPrice(uint256 id, uint256 price) public onlyVerifiedLessor(tripArray[indexOfID[id]].objectType) //modifier might not be neccessary -> check already happened before { require(tripArray[indexOfID[id]].lessor == msg.sender); require(tripArray[indexOfID[id]].reserved == false); tripArray[indexOfID[id]].price = price; } //lessors can delete their offers if not in use or reserved function deleteTrip(uint256 id) public { require(tripArray[indexOfID[id]].reserved == false); require(tripArray[indexOfID[id]].lessor == msg.sender); //trip can only be deleted if not reserved (coveres reserved and started) and if the function is called by the Lessor tripArray[indexOfID[id]] = tripArray[tripArray.length-1]; //set last element to current element in the Array, thus ovverriting the to be deleted element indexOfID[tripArray[tripArray.length-1].id] = indexOfID[id]; //set the index of the last element to the position it was now switched to delete tripArray[tripArray.length-1]; //delete last element since it got successfully moved indexOfID[id] = 0; //set index of deleted id = 0, indicating it got deleted tripArray.length--; //reduce length of array by one } //maybe restrict function to authorities as its a costly operation, deletes outdated trips from the platform (trips with expired latest return date), frees storage function deleteOutdatedTrips() public { for(uint256 i = 1; i < tripArray.length; i++) //beginning at 1 since 0 trip is not used { if(tripArray[i].endTime < block.timestamp) deleteTripInternal(i); } } //difference from above: Lessor does not have to be msg.sender, gets called by the PlatformContract to delete outdated Trips function deleteTripInternal(uint256 id) internal { require(tripArray[indexOfID[id]].reserved == false); //object can only be rented if not in use tripArray[indexOfID[id]] = tripArray[tripArray.length-1]; //set last element to current element in the Array, thus ovverriting the to be deleted element indexOfID[tripArray[tripArray.length-1].id] = indexOfID[id]; //set the index of the last element to the position it was now switched to delete tripArray[tripArray.length-1]; //delete last element since it got successfully moved indexOfID[id] = 0; //set index of deleted id = 0, indicating it got deleted tripArray.length--; //reduce length of array by one } //Get Trip Information Section function getTrip(uint256 id) public view returns(offer memory) //offer[] memory { return tripArray[indexOfID[id]]; //maybe mapindex has to be set to allow client to refind the trip -> probably better to set this client side when looping } function getLength() public view returns (uint256) //returns total amount of current trips { return tripArray.length; } //index +1 to make 0 distinguishable -no item found function getTripID(uint256 index) public view returns(uint256) { return tripArray[index].id; } //get sum of ratings and amount of ratings, need to be divided client side to retrive actual average rating -> costly operation function getRating(address a) public view returns( uint256[2] memory) { uint256[2] memory ratingArray; ratingArray[0] = usermap[a].rating; ratingArray[1] = usermap[a].ratingCount; return ratingArray; } /** function testGetTokenBalance(bool option) public view returns (uint256) { if(option == false) { return authorityTokens[msg.sender].totalSupply(); } else{ address def; return authorityTokens[def].totalSupply(); } } */ }
handle payment with elapsed time,´price of trip, from and to address
tokenManager.handlePayment(tripArray[indexOfID[id]].userDemandsEnd - tripArray[indexOfID[id]].started,tripArray[indexOfID[id]].price, msg.sender, tripArray[indexOfID[id]].lessor);
5,489,642
[ 1, 4110, 5184, 598, 9613, 813, 16, 131, 117, 8694, 434, 20654, 16, 628, 471, 358, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 1147, 1318, 18, 4110, 6032, 12, 25125, 1076, 63, 31806, 734, 63, 350, 65, 8009, 1355, 15058, 5708, 1638, 300, 20654, 1076, 63, 31806, 734, 63, 350, 65, 8009, 14561, 16, 25125, 1076, 63, 31806, 734, 63, 350, 65, 8009, 8694, 16, 1234, 18, 15330, 16, 20654, 1076, 63, 31806, 734, 63, 350, 65, 8009, 2656, 280, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "./Token.sol"; contract Policy { // initial state data SRXToken public token; // SRX token contract address public holder; // policy holder account address uint public target; // savings target uint public term; // policy term in months (30 day periods) uint public deposit; // initial deposit uint public riskRateBIPS; // annual risk rate in BIPS uint public inceptionDate; // Unix epoch timestamp uint public maturityDate; // Unix epoch timestamp // current state uint public period; // current period uint public savings; // value accrued to date uint public premiumsPaid; // accumulated premiums paid (for eventual no-claim rewards) uint[] public payments; // array of due dates (Unix epoch timestamp) keyed by period constructor( SRXToken _token, address _holder, uint _target, uint _term, uint _deposit, uint _riskRateBIPS ) { token = _token; holder = _holder; target = _target; term = _term; deposit = _deposit; riskRateBIPS = _riskRateBIPS; inceptionDate = block.timestamp; maturityDate = inceptionDate + term * 30 days; period = 0; savings = _deposit; premiumsPaid = 0; payments = new uint[](term+1); for(uint i = 0; i <= _term; i++) { payments[i] = inceptionDate + i * 30 days; } } function calculateCoverPremium() public view returns (uint) { return (target - (savings + calculateSavingsAnnuity())) * riskRateBIPS / 10000 / 12; } function calculateSavingsAnnuity() public view returns (uint) { if(period == 0) { return 0; } return (target - savings) / (term - period + 1); } /** * @dev Returns the value of the payment due. * For the inception period only cover is paid. * For the final period only the annuity is paid as the cover amount is zero. */ function calculatePayment() public view returns (uint) { if(period == 0) { return calculateCoverPremium() + deposit; } return calculateSavingsAnnuity() + calculateCoverPremium(); } function paymentSchedule() public view returns (uint[] memory) { return payments; } /** * @dev Returns true if, and only if, a payment is currently due. * It allows for payments to be made up to 48 hours in advance. */ function paymentIsDue() public view returns (bool) { uint nextDueDate = payments[period]; if(nextDueDate - 2 days > block.timestamp) { return false; } return true; } /** * @dev Returns true if, and only if, a payment is overdue. * It allows for payments to be made up to 48 hours after being due, * whereafter it is considered overdue. */ function paymentOverdue() public view returns (bool) { uint nextDueDate = payments[period]; if(nextDueDate + 2 days > block.timestamp) { return false; } return true; } /** * @dev Takes payment for the policy if, and only if, a payment is currently due. * Keeps separate track of current savings (for further calculations) and total premiums paid * (for future reward mechanisms related to no-claim policies). * Splits the payment into the annuity (currently held in the policy) and premium (sent to MCR). * * TODO: implement a late payment penalty mechanism (eg 10% overhead on missed payment within 7 days) * threshold for number of missed payments, and time overdue that will result in policy cancellation. * Cancellation will retain a portion of the savings as fees and refund the policyholder the remainder. */ function payPolicy() public returns (bool) { require(paymentIsDue(), "No payment is currently due."); uint _premium = calculateCoverPremium(); uint _annuity = calculateSavingsAnnuity(); uint paymentDue; if(period == 0) { paymentDue += deposit; savings += deposit; } paymentDue += _annuity + _premium; savings += _annuity; premiumsPaid += _premium; require(token.balanceOf(holder) >= paymentDue, "Insufficient tokens to pay policy."); require(token.approvedTransfer(holder, address(this), paymentDue), "Token transfer failed."); // TODO: move annuity to Savings Capital (yield farm) and premium amount to Risk Based Capital period++; return true; } }
* @dev Returns the value of the payment due. For the inception period only cover is paid. For the final period only the annuity is paid as the cover amount is zero./
function calculatePayment() public view returns (uint) { if(period == 0) { return calculateCoverPremium() + deposit; } return calculateSavingsAnnuity() + calculateCoverPremium(); }
12,854,104
[ 1, 1356, 326, 460, 434, 326, 5184, 6541, 18, 2457, 326, 316, 472, 3879, 1338, 5590, 353, 30591, 18, 2457, 326, 727, 3879, 1338, 326, 8226, 89, 560, 353, 30591, 487, 326, 5590, 3844, 353, 3634, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 6032, 1435, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 309, 12, 6908, 422, 374, 13, 288, 203, 5411, 327, 4604, 8084, 23890, 5077, 1435, 397, 443, 1724, 31, 203, 3639, 289, 203, 3639, 327, 4604, 55, 27497, 979, 13053, 560, 1435, 397, 4604, 8084, 23890, 5077, 5621, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@ensdomains/ens/contracts/ENS.sol"; import "@ensdomains/resolver/contracts/Resolver.sol"; import "./minting/IMinting.sol"; import "./onchainData/IonchainTokensData.sol"; /* * @title WNFT website Non-Fungible Token Standard basic implementation * @dev WNFT basic implementation */ contract WNFT is Ownable, ERC721URIStorage { struct SC { address SCaddress; bytes4 SCinterface; } Resolver private _ensResolver; ENS private _ens; // ens node bytes32 private _ensNodeID; AggregatorV3Interface private _priceFeed; uint256 public wnftPriceInUSDPOW8 = 1*(10**8); // for iterating all tokens uint[] private _keys; uint public amount = 0; // address(0) if this contract is still maintained, otherwise it means the owners recommend user to switch // to a new contract address private _contractSwitched; // address of a contract that says if minting is allowed or not IMinting private _mintingContract; // mapping of onchain metadata fields for the whole WNFT collection. mapping(string=>string) private _collectionOnchainMetadata; // mapping of allowed fields in collection mapping(string => bool) private _collectionMetadataFields; // array of possilbe field names of token metadata string[] private _collectionMetadataFieldNames; uint public collectionMetadataFieldNamesCount = 0; // mapping of allowed fields in token mapping(string => SC) private _tokensMetadataFields; // array of possilbe field names of token metadata string[] private _tokensMetadataFieldNames; uint public tokensMetadataFieldNamesCount = 0; mapping(bytes4 => bool) private _onchainMetadataInterface; // true if the field (string) is set for the WNFT token id (uint256) // mapping(uint256 => mapping(string=>bool)) private _tokens_onchain_metadata; // URI for metadata for the whole WNFT collection // offchain per collection info string private _wnftUri; // emitted when WNFT contract owners add a new field of metadata for tokens // when new field is allowed and defined for all tokens event TokenOnchainMetadataFieldAdded(string field, SC fieldSc); // emitted when WNFT contract owners add a new field of onchain metadata field for the WNFT collection // when new field of meta data allowed/defined for the collection event CollectionOnchainMetadataFieldAdded(string field); // emitted when owner switches from this contract to another event ContractSwitch(address newContract); // check if the onchain field interface equals a given interface. // If not it implies that either token field is undefined or the interface of the field // doesn't equal the interface of the function being called. modifier tokenOnchainFieldAllowed(string memory field, bytes4 SCinterface) { require(_tokensMetadataFields[field].SCinterface == SCinterface, "WNFT: Token metadata error"); _; } // check if the onchain field is defined for the WNFT collection // checks that owner of contract allows and defined the field modifier collectionOnchainFieldAllowed(string memory fieldName) { require(_collectionMetadataFields[fieldName] == true, "WNFT: Collection metadata error"); _; } // if minting is allowed for specific token modifier canMintMod(address to, uint256 tokenId) { require (_mintingContract.canMint(to, tokenId), "WNFT: Not allowed"); _; } // if minting is allowed for specific token modifier onlyTokenOwner(uint256 tokenId) { require(super._isApprovedOrOwner(msg.sender, tokenId), "WNFT: Owner only"); _; } modifier enoughFunds(uint value) { require( value - (wnftPriceInUSDPOW8 * 10**18/uint(_getLatestPrice())) < 10, "Wei dont match"); _; } // metadata of the whole WNFT collection /* * @dev Constructor function */ constructor (string memory name, string memory symbol, IMinting newMintingContract, Resolver ensResolver, ENS ens, bytes32 ensNode, AggregatorV3Interface newPriceFeed) ERC721(name, symbol) Ownable() { _mintingContract = newMintingContract; _ensResolver = ensResolver; _ens = ens; _ensNodeID = ensNode; _priceFeed = newPriceFeed; _onchainMetadataInterface[0x661f2816] = true; _onchainMetadataInterface[0x2421c19b] = true; } /* * @dev Sets 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 calldata uri) external onlyTokenOwner(tokenId) { super._setTokenURI(tokenId, uri); } /* * @dev Sets the URI for the WNFT collection * @param uri string URI to assign */ function setWnftUri(string calldata uri) external onlyOwner { _wnftUri = uri; } /* * @dev Function to add more onchain metadata fields for the tokens * the field_rules_sc points to a smart contract with Interface valid_data(tokenID, value) function * WNFT contract owners first add fields (name, weight etc.), with a connection to a smart contract that * sets the validity rules for those fields. Then users can use setTokenMetadata function to set * values for the fields. * @param @SCinterface The address of the interface to process the field type * @param @SCaddress The address of the interface to process the field type * @param @field The name of the field where the data will be stored. */ function addTokenOnchainMetadataField(bytes4 SCinterface, address SCaddress, string memory fieldName) external onlyOwner { // TODO: check that field is not defined yet if(_tokensMetadataFields[fieldName].SCaddress==address(0)){ _tokensMetadataFieldNames.push(fieldName); tokensMetadataFieldNamesCount++; } // check SCinterface is valid require(_onchainMetadataInterface[SCinterface], "SCInterface not valid"); // verify interface of the smart contract //IERC165 _SCaddress = IERC165(SCaddress); require(IERC165(SCaddress).supportsInterface(SCinterface), "SCInterface not supported"); // set _tokensMetadataFields of the field _tokensMetadataFields[fieldName].SCinterface = SCinterface; _tokensMetadataFields[fieldName].SCaddress = SCaddress; emit TokenOnchainMetadataFieldAdded(fieldName, _tokensMetadataFields[fieldName]); } // four functions to set token onchain metadata function setTokenOnchainMetadataString(uint256 tokenId, string calldata field, string calldata value) external tokenOnchainFieldAllowed(field, 0x661f2816) onlyTokenOwner(tokenId) { IonchainTokenDataString(_tokensMetadataFields[field].SCaddress).setData(tokenId, value); } function setTokenOnchainMetadataUint(uint256 tokenId, string calldata field, uint value) external tokenOnchainFieldAllowed(field, 0x2421c19b) onlyTokenOwner(tokenId) { IonchainTokenDataUint(_tokensMetadataFields[field].SCaddress).setData(tokenId, value); } /* * @dev Function to add fields for collection onchain metadata * @param @fieldName The address that will receive the minted tokens. * will also emit event of CollectionOnchainMetadataFieldAdded with field name */ function addCollectionOnchainMetadataField(string memory fieldName) external onlyOwner { _collectionMetadataFields[fieldName] = true; emit CollectionOnchainMetadataFieldAdded(fieldName); } /* * @dev Function to set onchain metadata for collection for specific field * @param @fieldName The field name to set * @param @fieldValue The field value to set */ function setCollectionOnchainMetadata(string calldata fieldName, string calldata fieldValue) external onlyOwner { //vCollectionOnchainFieldAllowed(fieldName); if(_collectionMetadataFields[fieldName]!=true){ _collectionMetadataFieldNames.push(fieldName); collectionMetadataFieldNamesCount++; } _collectionOnchainMetadata[fieldName] = fieldValue; } /* * @dev Function to set a minting contract * @param @newContract The new min */ function setMintingContract(IMinting newContract) external onlyOwner { _mintingContract = newContract; } /* * @dev Function to set contract switched flag * @param @newContract The address of the new contract * will also emit event of ContractSwitch with newContract */ function setContractSwitched(address newContract) external onlyOwner { _contractSwitched = newContract; emit ContractSwitch(newContract); } /* * @dev Function to set ens content hash * @param @hash new content hash for ens */ function setENSContenthash(bytes calldata hash) external onlyOwner { _ensResolver.setContenthash(_ensNodeID, hash); } /* * @dev Function to set the ens resolver * @param @ensResolver ens resolver to set in the contract */ function setENSResolver(Resolver ensResolver) external onlyOwner { _ensResolver = ensResolver; } function setENSRegistar(ENS ensRegistar) external onlyOwner { _ens = ensRegistar; } /* * @dev function to trasnfer ens name ownership * @param @newOwner The new owner for the ens name */ function transferENSName(address newOwner) external onlyOwner { // TODO: safe transfer _ens.setOwner(_ensNodeID, newOwner); } /* * @dev Function to setEnsNode * @param @ensNode The ens node to be controled */ function setENSNodeID(bytes32 ensNode) external onlyOwner { _ensNodeID = ensNode; } /* * @dev Function to set the minting token price * @param @tokenPrice The USD value of the token price for minting */ function setTokenPrice(uint256 tokenPriceInTenthOfCent) external onlyOwner { wnftPriceInUSDPOW8 = tokenPriceInTenthOfCent*(10**5); } /* * @dev Function to mint tokens * @param @to The address that will receive the minted tokens. * @param @tokenId The token id to mint. */ function mint(address to, uint256 tokenId) external payable enoughFunds(msg.value) canMintMod(to, tokenId) { _doMint(to, tokenId); } /* * @dev Function to mint tokens and set their URI in one action * @param @to The address that will receive the minted tokens. * @param @tokenId The token id to mint. * @param @uri string URI to assign */ function mintWithTokenURI(address to, uint256 tokenId, string calldata uri) external payable enoughFunds(msg.value) canMintMod(to, tokenId) { _doMint(to, tokenId); // set token URI super._setTokenURI(tokenId, uri); } /* * @dev Returns the URI of the WNFT collection * @return {string} WNFT uri for offchain meta data * May return an empty string. */ function wnftUri() external view returns (string memory) { return _wnftUri; } function tokenOnchainMetadataString(uint256 tokenId, string memory field) external view tokenOnchainFieldAllowed(field, 0x661f2816) returns (string memory) { return IonchainTokenDataString(_tokensMetadataFields[field].SCaddress).getData(tokenId); } function tokenOnchainMetadataUint(uint256 tokenId, string memory field) external view tokenOnchainFieldAllowed(field, 0x2421c19b) returns (uint) { return IonchainTokenDataUint(_tokensMetadataFields[field].SCaddress).getData(tokenId); } /* * @dev Function to get the collectionOnchainMetadata for specific field * @param @fieldName The field name to get data for * @return {string} Value of the collection onchain metadata for specific field */ function collectionOnchainMetadata(string memory fieldName) public view returns (string memory) { return _collectionOnchainMetadata[fieldName]; } /* * @dev Function to get the minting contract * @return {IMinting} The minting contract */ function mintingContract() external view returns (IMinting) { return _mintingContract; } function ensContenthash() public view returns (bytes memory){ return _ensResolver.contenthash(_ensNodeID); } /* * @dev get the contract switched flag * @return {address} The contract switch address */ function contractSwitched() external view returns (address) { return _contractSwitched; } /* * @dev Function to get ens resolver * @return {Resolver} the current resolver defined */ function ENSResolver() external view returns (Resolver) { return _ensResolver; } /* * @dev Function will return the ens registar contract * @return {ENS} ens registar contract returned */ function ENSRegistar() external view returns (ENS) { return _ens; } /* * @dev Function will return the ens node id * @return {bytes32} ens node id returned */ function ENSNodeID() external view returns (bytes32) { return _ensNodeID; } /* * @dev Function to check minting a token * @param @to The address that will receive the minted tokens. * @param @tokenId The token id to mint. * @return {bool} A boolean that indicates if the operation was successful. */ function canMint(address to, uint256 tokenId) external view returns (bool) { // check if taken return ((!super._exists(tokenId)) && _mintingContract.canMint(to, tokenId)); } /* * @dev Function to get token by incremental counter index * @param @i uint The index using incremental token id * @return {uint} tokenId of real tokenId */ function NthToken(uint i) external view returns (uint) { require(i < amount, "Token doesn't exist"); return _keys[i]; } //return Array of structure function getCollectionMetadataField() public view returns (string[] memory, string[] memory){ string[] memory id = new string[](collectionMetadataFieldNamesCount); string[] memory vals = new string[](collectionMetadataFieldNamesCount); for (uint i = 0; i < collectionMetadataFieldNamesCount; i++) { id[i] = _collectionMetadataFieldNames[i]; vals[i] = collectionOnchainMetadata(_collectionMetadataFieldNames[i]); } return (id, vals); } //return Array of structure function getTokenMetadataField() public view returns (string[] memory, address[] memory, bytes4[] memory){ string[] memory id = new string[](tokensMetadataFieldNamesCount); address[] memory scAddresses = new address[](tokensMetadataFieldNamesCount); bytes4[] memory scInterfaces = new bytes4[](tokensMetadataFieldNamesCount); for (uint i = 0; i < tokensMetadataFieldNamesCount; i++) { id[i] = _tokensMetadataFieldNames[i]; scAddresses[i] = _tokensMetadataFields[_tokensMetadataFieldNames[i]].SCaddress; scInterfaces[i] = _tokensMetadataFields[_tokensMetadataFieldNames[i]].SCinterface; } return (id, scAddresses, scInterfaces); } function tokenExists(uint256 tokenId) public view returns (bool){ return super._exists(tokenId); } /* * @dev function to do internal minting * @notice function is not checking balance or other things * @param @to who to mint for * @param @tokenId tokenId */ function _doMint(address to, uint256 tokenId) internal { _mint(to, tokenId); // add to tokens index _keys.push(tokenId); amount = amount + 1; } /* * @dev Function to get token by incremental counter index * @return {int} latest ETH/USD price from oracle */ function _getLatestPrice() internal view returns (int) { ( , int price, , , ) = _priceFeed.latestRoundData(); // for ETH / USD price is scaled up by 10 ** 8 return price; } }
check if the onchain field is defined for the WNFT collection checks that owner of contract allows and defined the field
modifier collectionOnchainFieldAllowed(string memory fieldName) { require(_collectionMetadataFields[fieldName] == true, "WNFT: Collection metadata error"); _; }
1,017,880
[ 1, 1893, 309, 326, 603, 5639, 652, 353, 2553, 364, 326, 678, 50, 4464, 1849, 4271, 716, 3410, 434, 6835, 5360, 471, 2553, 326, 652, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1849, 1398, 5639, 974, 5042, 12, 1080, 3778, 4289, 13, 288, 203, 3639, 2583, 24899, 5548, 2277, 2314, 63, 16163, 65, 422, 638, 16, 315, 5665, 4464, 30, 2200, 1982, 555, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "../ManagerProxyTarget.sol"; import "./IBondingManager.sol"; import "../libraries/SortedDoublyLL.sol"; import "../libraries/MathUtils.sol"; import "../libraries/PreciseMathUtils.sol"; import "./libraries/EarningsPool.sol"; import "./libraries/EarningsPoolLIP36.sol"; import "../token/ILivepeerToken.sol"; import "../token/IMinter.sol"; import "../rounds/IRoundsManager.sol"; import "../snapshots/IMerkleSnapshot.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title BondingManager * @notice Manages bonding, transcoder and rewards/fee accounting related operations of the Livepeer protocol */ contract BondingManager is ManagerProxyTarget, IBondingManager { using SafeMath for uint256; using SortedDoublyLL for SortedDoublyLL.Data; using EarningsPool for EarningsPool.Data; using EarningsPoolLIP36 for EarningsPool.Data; // Constants // Occurances are replaced at compile time // and computed to a single value if possible by the optimizer uint256 constant MAX_FUTURE_ROUND = 2**256 - 1; // Time between unbonding and possible withdrawl in rounds uint64 public unbondingPeriod; // Represents a transcoder's current state struct Transcoder { uint256 lastRewardRound; // Last round that the transcoder called reward uint256 rewardCut; // % of reward paid to transcoder by a delegator uint256 feeShare; // % of fees paid to delegators by transcoder mapping(uint256 => EarningsPool.Data) earningsPoolPerRound; // Mapping of round => earnings pool for the round uint256 lastActiveStakeUpdateRound; // Round for which the stake was last updated while the transcoder is active uint256 activationRound; // Round in which the transcoder became active - 0 if inactive uint256 deactivationRound; // Round in which the transcoder will become inactive uint256 activeCumulativeRewards; // The transcoder's cumulative rewards that are active in the current round uint256 cumulativeRewards; // The transcoder's cumulative rewards (earned via the its active staked rewards and its reward cut). uint256 cumulativeFees; // The transcoder's cumulative fees (earned via the its active staked rewards and its fee share) uint256 lastFeeRound; // Latest round in which the transcoder received fees } // The various states a transcoder can be in enum TranscoderStatus { NotRegistered, Registered } // Represents a delegator's current state struct Delegator { uint256 bondedAmount; // The amount of bonded tokens uint256 fees; // The amount of fees collected address delegateAddress; // The address delegated to uint256 delegatedAmount; // The amount of tokens delegated to the delegator uint256 startRound; // The round the delegator transitions to bonded phase and is delegated to someone uint256 lastClaimRound; // The last round during which the delegator claimed its earnings uint256 nextUnbondingLockId; // ID for the next unbonding lock created mapping(uint256 => UnbondingLock) unbondingLocks; // Mapping of unbonding lock ID => unbonding lock } // The various states a delegator can be in enum DelegatorStatus { Pending, Bonded, Unbonded } // Represents an amount of tokens that are being unbonded struct UnbondingLock { uint256 amount; // Amount of tokens being unbonded uint256 withdrawRound; // Round at which unbonding period is over and tokens can be withdrawn } // Keep track of the known transcoders and delegators mapping(address => Delegator) private delegators; mapping(address => Transcoder) private transcoders; // The total active stake (sum of the stake of active set members) for the current round uint256 public currentRoundTotalActiveStake; // The total active stake (sum of the stake of active set members) for the next round uint256 public nextRoundTotalActiveStake; // The transcoder pool is used to keep track of the transcoders that are eligible for activation. // The pool keeps track of the pending active set in round N and the start of round N + 1 transcoders // in the pool are locked into the active set for round N + 1 SortedDoublyLL.Data private transcoderPool; // Check if sender is TicketBroker modifier onlyTicketBroker() { _onlyTicketBroker(); _; } // Check if sender is RoundsManager modifier onlyRoundsManager() { _onlyRoundsManager(); _; } // Check if sender is Verifier modifier onlyVerifier() { _onlyVerifier(); _; } // Check if current round is initialized modifier currentRoundInitialized() { _currentRoundInitialized(); _; } // Automatically claim earnings from lastClaimRound through the current round modifier autoClaimEarnings() { _autoClaimEarnings(); _; } /** * @notice BondingManager constructor. Only invokes constructor of base Manager contract with provided Controller address * @dev This constructor will not initialize any state variables besides `controller`. The following setter functions * should be used to initialize state variables post-deployment: * - setUnbondingPeriod() * - setNumActiveTranscoders() * - setMaxEarningsClaimsRounds() * @param _controller Address of Controller that this contract will be registered with */ constructor(address _controller) Manager(_controller) {} /** * @notice Set unbonding period. Only callable by Controller owner * @param _unbondingPeriod Rounds between unbonding and possible withdrawal */ function setUnbondingPeriod(uint64 _unbondingPeriod) external onlyControllerOwner { unbondingPeriod = _unbondingPeriod; emit ParameterUpdate("unbondingPeriod"); } /** * @notice Set maximum number of active transcoders. Only callable by Controller owner * @param _numActiveTranscoders Number of active transcoders */ function setNumActiveTranscoders(uint256 _numActiveTranscoders) external onlyControllerOwner { transcoderPool.setMaxSize(_numActiveTranscoders); emit ParameterUpdate("numActiveTranscoders"); } /** * @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it * @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR * @param _rewardCut % of reward paid to transcoder by a delegator * @param _feeShare % of fees paid to delegators by a transcoder */ function transcoder(uint256 _rewardCut, uint256 _feeShare) external { transcoderWithHint(_rewardCut, _feeShare, address(0), address(0)); } /** * @notice Delegate stake towards a specific address * @param _amount The amount of tokens to stake * @param _to The address of the transcoder to stake towards */ function bond(uint256 _amount, address _to) external { bondWithHint(_amount, _to, address(0), address(0), address(0), address(0)); } /** * @notice Unbond an amount of the delegator's bonded stake * @param _amount Amount of tokens to unbond */ function unbond(uint256 _amount) external { unbondWithHint(_amount, address(0), address(0)); } /** * @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status * @param _unbondingLockId ID of unbonding lock to rebond with */ function rebond(uint256 _unbondingLockId) external { rebondWithHint(_unbondingLockId, address(0), address(0)); } /** * @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status * @param _to Address of delegate * @param _unbondingLockId ID of unbonding lock to rebond with */ function rebondFromUnbonded(address _to, uint256 _unbondingLockId) external { rebondFromUnbondedWithHint(_to, _unbondingLockId, address(0), address(0)); } /** * @notice Withdraws tokens for an unbonding lock that has existed through an unbonding period * @param _unbondingLockId ID of unbonding lock to withdraw with */ function withdrawStake(uint256 _unbondingLockId) external whenSystemNotPaused currentRoundInitialized { Delegator storage del = delegators[msg.sender]; UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId]; require(isValidUnbondingLock(msg.sender, _unbondingLockId), "invalid unbonding lock ID"); require( lock.withdrawRound <= roundsManager().currentRound(), "withdraw round must be before or equal to the current round" ); uint256 amount = lock.amount; uint256 withdrawRound = lock.withdrawRound; // Delete unbonding lock delete del.unbondingLocks[_unbondingLockId]; // Tell Minter to transfer stake (LPT) to the delegator minter().trustedTransferTokens(msg.sender, amount); emit WithdrawStake(msg.sender, _unbondingLockId, amount, withdrawRound); } /** * @notice Withdraws fees to the caller */ function withdrawFees(address payable _recipient, uint256 _amount) external whenSystemNotPaused currentRoundInitialized autoClaimEarnings { require(_recipient != address(0), "invalid recipient"); uint256 fees = delegators[msg.sender].fees; require(fees >= _amount, "insufficient fees to withdraw"); delegators[msg.sender].fees = fees.sub(_amount); // Tell Minter to transfer fees (ETH) to the address minter().trustedWithdrawETH(_recipient, _amount); emit WithdrawFees(msg.sender, _recipient, _amount); } /** * @notice Mint token rewards for an active transcoder and its delegators */ function reward() external { rewardWithHint(address(0), address(0)); } /** * @notice Update transcoder's fee pool. Only callable by the TicketBroker * @param _transcoder Transcoder address * @param _fees Fees to be added to the fee pool */ function updateTranscoderWithFees( address _transcoder, uint256 _fees, uint256 _round ) external whenSystemNotPaused onlyTicketBroker { // Silence unused param compiler warning _round; require(isRegisteredTranscoder(_transcoder), "transcoder must be registered"); uint256 currentRound = roundsManager().currentRound(); Transcoder storage t = transcoders[_transcoder]; uint256 lastRewardRound = t.lastRewardRound; uint256 activeCumulativeRewards = t.activeCumulativeRewards; // LIP-36: Add fees for the current round instead of '_round' // https://github.com/livepeer/LIPs/issues/35#issuecomment-673659199 EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound]; EarningsPool.Data memory prevEarningsPool = latestCumulativeFactorsPool(t, currentRound.sub(1)); // if transcoder hasn't called 'reward()' for '_round' its 'transcoderFeeShare', 'transcoderRewardCut' and 'totalStake' // on the 'EarningsPool' for '_round' would not be initialized and the fee distribution wouldn't happen as expected // for cumulative fee calculation this would result in division by zero. if (currentRound > lastRewardRound) { earningsPool.setCommission(t.rewardCut, t.feeShare); uint256 lastUpdateRound = t.lastActiveStakeUpdateRound; if (lastUpdateRound < currentRound) { earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake); } // If reward() has not been called yet in the current round, then the transcoder's activeCumulativeRewards has not // yet been set in for the round. When the transcoder calls reward() its activeCumulativeRewards will be set to its // current cumulativeRewards. So, we can just use the transcoder's cumulativeRewards here because this will become // the transcoder's activeCumulativeRewards if it calls reward() later on in the current round activeCumulativeRewards = t.cumulativeRewards; } uint256 totalStake = earningsPool.totalStake; if (prevEarningsPool.cumulativeRewardFactor == 0 && lastRewardRound == currentRound) { // if transcoder called reward for 'currentRound' but not for 'currentRound - 1' (missed reward call) // retroactively calculate what its cumulativeRewardFactor would have been for 'currentRound - 1' (cfr. previous lastRewardRound for transcoder) // based on rewards for currentRound IMinter mtr = minter(); uint256 rewards = PreciseMathUtils.percOf( mtr.currentMintableTokens().add(mtr.currentMintedTokens()), totalStake, currentRoundTotalActiveStake ); uint256 transcoderCommissionRewards = MathUtils.percOf(rewards, earningsPool.transcoderRewardCut); uint256 delegatorsRewards = rewards.sub(transcoderCommissionRewards); prevEarningsPool.cumulativeRewardFactor = PreciseMathUtils.percOf( earningsPool.cumulativeRewardFactor, totalStake, delegatorsRewards.add(totalStake) ); } uint256 delegatorsFees = MathUtils.percOf(_fees, earningsPool.transcoderFeeShare); uint256 transcoderCommissionFees = _fees.sub(delegatorsFees); // Calculate the fees earned by the transcoder's earned rewards uint256 transcoderRewardStakeFees = PreciseMathUtils.percOf( delegatorsFees, activeCumulativeRewards, totalStake ); // Track fees earned by the transcoder based on its earned rewards and feeShare t.cumulativeFees = t.cumulativeFees.add(transcoderRewardStakeFees).add(transcoderCommissionFees); // Update cumulative fee factor with new fees // The cumulativeFeeFactor is used to calculate fees for all delegators including the transcoder (self-delegated) // Note that delegatorsFees includes transcoderRewardStakeFees, but no delegator will claim that amount using // the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeFees field earningsPool.updateCumulativeFeeFactor(prevEarningsPool, delegatorsFees); t.lastFeeRound = currentRound; } /** * @notice Slash a transcoder. Only callable by the Verifier * @param _transcoder Transcoder address * @param _finder Finder that proved a transcoder violated a slashing condition. Null address if there is no finder * @param _slashAmount Percentage of transcoder bond to be slashed * @param _finderFee Percentage of penalty awarded to finder. Zero if there is no finder */ function slashTranscoder( address _transcoder, address _finder, uint256 _slashAmount, uint256 _finderFee ) external whenSystemNotPaused onlyVerifier { Delegator storage del = delegators[_transcoder]; if (del.bondedAmount > 0) { uint256 penalty = MathUtils.percOf(delegators[_transcoder].bondedAmount, _slashAmount); // If active transcoder, resign it if (transcoderPool.contains(_transcoder)) { resignTranscoder(_transcoder); } // Decrease bonded stake del.bondedAmount = del.bondedAmount.sub(penalty); // If still bonded decrease delegate's delegated amount if (delegatorStatus(_transcoder) == DelegatorStatus.Bonded) { delegators[del.delegateAddress].delegatedAmount = delegators[del.delegateAddress].delegatedAmount.sub( penalty ); } // Account for penalty uint256 burnAmount = penalty; // Award finder fee if there is a finder address if (_finder != address(0)) { uint256 finderAmount = MathUtils.percOf(penalty, _finderFee); minter().trustedTransferTokens(_finder, finderAmount); // Minter burns the slashed funds - finder reward minter().trustedBurnTokens(burnAmount.sub(finderAmount)); emit TranscoderSlashed(_transcoder, _finder, penalty, finderAmount); } else { // Minter burns the slashed funds minter().trustedBurnTokens(burnAmount); emit TranscoderSlashed(_transcoder, address(0), penalty, 0); } } else { emit TranscoderSlashed(_transcoder, _finder, 0, 0); } } /** * @notice Claim token pools shares for a delegator from its lastClaimRound through the end round * @param _endRound The last round for which to claim token pools shares for a delegator */ function claimEarnings(uint256 _endRound) external whenSystemNotPaused currentRoundInitialized { // Silence unused param compiler warning _endRound; _autoClaimEarnings(); } /** * @notice Called during round initialization to set the total active stake for the round. Only callable by the RoundsManager */ function setCurrentRoundTotalActiveStake() external onlyRoundsManager { currentRoundTotalActiveStake = nextRoundTotalActiveStake; } /** * @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it using an optional list hint * @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR. If the caller is going to be added to the pool, the * caller can provide an optional hint for the insertion position in the pool via the `_newPosPrev` and `_newPosNext` params. A linear search will * be executed starting at the hint to find the correct position - in the best case, the hint is the correct position so no search is executed. * See SortedDoublyLL.sol for details on list hints * @param _rewardCut % of reward paid to transcoder by a delegator * @param _feeShare % of fees paid to delegators by a transcoder * @param _newPosPrev Address of previous transcoder in pool if the caller joins the pool * @param _newPosNext Address of next transcoder in pool if the caller joins the pool */ function transcoderWithHint( uint256 _rewardCut, uint256 _feeShare, address _newPosPrev, address _newPosNext ) public whenSystemNotPaused currentRoundInitialized { require(!roundsManager().currentRoundLocked(), "can't update transcoder params, current round is locked"); require(MathUtils.validPerc(_rewardCut), "invalid rewardCut percentage"); require(MathUtils.validPerc(_feeShare), "invalid feeShare percentage"); require(isRegisteredTranscoder(msg.sender), "transcoder must be registered"); Transcoder storage t = transcoders[msg.sender]; uint256 currentRound = roundsManager().currentRound(); require( !isActiveTranscoder(msg.sender) || t.lastRewardRound == currentRound, "caller can't be active or must have already called reward for the current round" ); t.rewardCut = _rewardCut; t.feeShare = _feeShare; if (!transcoderPool.contains(msg.sender)) { tryToJoinActiveSet( msg.sender, delegators[msg.sender].delegatedAmount, currentRound.add(1), _newPosPrev, _newPosNext ); } emit TranscoderUpdate(msg.sender, _rewardCut, _feeShare); } /** * @notice Delegates stake "on behalf of" another address towards a specific address * and updates the transcoder pool using optional list hints if needed * @dev If the caller is decreasing the stake of its old delegate in the transcoder pool, the caller can provide an optional hint * for the insertion position of the old delegate via the `_oldDelegateNewPosPrev` and `_oldDelegateNewPosNext` params. * If the caller is delegating to a delegate that is in the transcoder pool, the caller can provide an optional hint for the * insertion position of the delegate via the `_currDelegateNewPosPrev` and `_currDelegateNewPosNext` params. * In both cases, a linear search will be executed starting at the hint to find the correct position. In the best case, the hint * is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints * @param _amount The amount of tokens to stake. * @param _owner The address of the owner of the bond * @param _to The address of the transcoder to stake towards * @param _oldDelegateNewPosPrev The address of the previous transcoder in the pool for the old delegate * @param _oldDelegateNewPosNext The address of the next transcoder in the pool for the old delegate * @param _currDelegateNewPosPrev The address of the previous transcoder in the pool for the current delegate * @param _currDelegateNewPosNext The address of the next transcoder in the pool for the current delegate */ function bondForWithHint( uint256 _amount, address _owner, address _to, address _oldDelegateNewPosPrev, address _oldDelegateNewPosNext, address _currDelegateNewPosPrev, address _currDelegateNewPosNext ) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings { Delegator storage del = delegators[_owner]; uint256 currentRound = roundsManager().currentRound(); // Amount to delegate uint256 delegationAmount = _amount; // Current delegate address currentDelegate = del.delegateAddress; // Current bonded amount uint256 currentBondedAmount = del.bondedAmount; if (delegatorStatus(_owner) == DelegatorStatus.Unbonded) { // New delegate // Set start round // Don't set start round if delegator is in pending state because the start round would not change del.startRound = currentRound.add(1); // Unbonded state = no existing delegate and no bonded stake // Thus, delegation amount = provided amount } else if (currentBondedAmount > 0 && currentDelegate != _to) { // A registered transcoder cannot delegate its bonded stake toward another address // because it can only be delegated toward itself // In the future, if delegation towards another registered transcoder as an already // registered transcoder becomes useful (i.e. for transitive delegation), this restriction // could be removed require(!isRegisteredTranscoder(_owner), "registered transcoders can't delegate towards other addresses"); // Changing delegate // Set start round del.startRound = currentRound.add(1); // Update amount to delegate with previous delegation amount delegationAmount = delegationAmount.add(currentBondedAmount); decreaseTotalStake(currentDelegate, currentBondedAmount, _oldDelegateNewPosPrev, _oldDelegateNewPosNext); } { Transcoder storage newDelegate = transcoders[_to]; EarningsPool.Data storage currPool = newDelegate.earningsPoolPerRound[currentRound]; if (currPool.cumulativeRewardFactor == 0) { currPool.cumulativeRewardFactor = cumulativeFactorsPool(newDelegate, newDelegate.lastRewardRound) .cumulativeRewardFactor; } if (currPool.cumulativeFeeFactor == 0) { currPool.cumulativeFeeFactor = cumulativeFactorsPool(newDelegate, newDelegate.lastFeeRound) .cumulativeFeeFactor; } } // cannot delegate to someone without having bonded stake require(delegationAmount > 0, "delegation amount must be greater than 0"); // Update delegate del.delegateAddress = _to; // Update bonded amount del.bondedAmount = currentBondedAmount.add(_amount); increaseTotalStake(_to, delegationAmount, _currDelegateNewPosPrev, _currDelegateNewPosNext); if (_amount > 0) { // Transfer the LPT to the Minter livepeerToken().transferFrom(msg.sender, address(minter()), _amount); } emit Bond(_to, currentDelegate, _owner, _amount, del.bondedAmount); } /** * @notice Delegates stake towards a specific address and updates the transcoder pool using optional list hints if needed * @dev If the caller is decreasing the stake of its old delegate in the transcoder pool, the caller can provide an optional hint * for the insertion position of the old delegate via the `_oldDelegateNewPosPrev` and `_oldDelegateNewPosNext` params. * If the caller is delegating to a delegate that is in the transcoder pool, the caller can provide an optional hint for the * insertion position of the delegate via the `_currDelegateNewPosPrev` and `_currDelegateNewPosNext` params. * In both cases, a linear search will be executed starting at the hint to find the correct position. In the best case, the hint * is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints * @param _amount The amount of tokens to stake. * @param _to The address of the transcoder to stake towards * @param _oldDelegateNewPosPrev The address of the previous transcoder in the pool for the old delegate * @param _oldDelegateNewPosNext The address of the next transcoder in the pool for the old delegate * @param _currDelegateNewPosPrev The address of the previous transcoder in the pool for the current delegate * @param _currDelegateNewPosNext The address of the next transcoder in the pool for the current delegate */ function bondWithHint( uint256 _amount, address _to, address _oldDelegateNewPosPrev, address _oldDelegateNewPosNext, address _currDelegateNewPosPrev, address _currDelegateNewPosNext ) public { bondForWithHint( _amount, msg.sender, _to, _oldDelegateNewPosPrev, _oldDelegateNewPosNext, _currDelegateNewPosPrev, _currDelegateNewPosNext ); } /** * @notice Transfers ownership of a bond to a new delegator using optional hints if needed * * If the receiver is already bonded to a different delegate than the bond owner then the stake goes * to the receiver's delegate otherwise the receiver's delegate is set as the owner's delegate * * @dev If the original delegate is in the transcoder pool, the caller can provide an optional hint for the * insertion position of the delegate via the `_oldDelegateNewPosPrev` and `_oldDelegateNewPosNext` params. * If the target delegate is in the transcoder pool, the caller can provide an optional hint for the * insertion position of the delegate via the `_newDelegateNewPosPrev` and `_newDelegateNewPosNext` params. * * In both cases, a linear search will be executed starting at the hint to find the correct position. In the best case, the hint * is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints * @param _delegator Receiver of the bond * @param _amount Portion of the bond to transfer to receiver * @param _oldDelegateNewPosPrev Address of previous transcoder in pool if the delegate remains in the pool * @param _oldDelegateNewPosNext Address of next transcoder in pool if the delegate remains in the pool * @param _newDelegateNewPosPrev Address of previous transcoder in pool if the delegate is in the pool * @param _newDelegateNewPosNext Address of next transcoder in pool if the delegate is in the pool */ function transferBond( address _delegator, uint256 _amount, address _oldDelegateNewPosPrev, address _oldDelegateNewPosNext, address _newDelegateNewPosPrev, address _newDelegateNewPosNext ) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings { Delegator storage oldDel = delegators[msg.sender]; // Cache delegate address of caller before unbondWithHint because // if unbondWithHint is for a full unbond the caller's delegate address will be set to null address oldDelDelegate = oldDel.delegateAddress; unbondWithHint(_amount, _oldDelegateNewPosPrev, _oldDelegateNewPosNext); Delegator storage newDel = delegators[_delegator]; uint256 oldDelUnbondingLockId = oldDel.nextUnbondingLockId.sub(1); uint256 withdrawRound = oldDel.unbondingLocks[oldDelUnbondingLockId].withdrawRound; // Burn lock for current owner delete oldDel.unbondingLocks[oldDelUnbondingLockId]; // Create lock for new owner uint256 newDelUnbondingLockId = newDel.nextUnbondingLockId; newDel.unbondingLocks[newDelUnbondingLockId] = UnbondingLock({ amount: _amount, withdrawRound: withdrawRound }); newDel.nextUnbondingLockId = newDel.nextUnbondingLockId.add(1); emit TransferBond(msg.sender, _delegator, oldDelUnbondingLockId, newDelUnbondingLockId, _amount); // Claim earnings for receiver before processing unbonding lock uint256 currentRound = roundsManager().currentRound(); uint256 lastClaimRound = newDel.lastClaimRound; if (lastClaimRound < currentRound) { updateDelegatorWithEarnings(_delegator, currentRound, lastClaimRound); } // Rebond lock for new owner if (newDel.delegateAddress == address(0)) { newDel.delegateAddress = oldDelDelegate; } // Move to Pending state if receiver is currently in Unbonded state if (delegatorStatus(_delegator) == DelegatorStatus.Unbonded) { newDel.startRound = currentRound.add(1); } // Process rebond using unbonding lock processRebond(_delegator, newDelUnbondingLockId, _newDelegateNewPosPrev, _newDelegateNewPosNext); } /** * @notice Unbond an amount of the delegator's bonded stake and updates the transcoder pool using an optional list hint if needed * @dev If the caller remains in the transcoder pool, the caller can provide an optional hint for its insertion position in the * pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position. * In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints * @param _amount Amount of tokens to unbond * @param _newPosPrev Address of previous transcoder in pool if the caller remains in the pool * @param _newPosNext Address of next transcoder in pool if the caller remains in the pool */ function unbondWithHint( uint256 _amount, address _newPosPrev, address _newPosNext ) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings { require(delegatorStatus(msg.sender) == DelegatorStatus.Bonded, "caller must be bonded"); Delegator storage del = delegators[msg.sender]; require(_amount > 0, "unbond amount must be greater than 0"); require(_amount <= del.bondedAmount, "amount is greater than bonded amount"); address currentDelegate = del.delegateAddress; uint256 currentRound = roundsManager().currentRound(); uint256 withdrawRound = currentRound.add(unbondingPeriod); uint256 unbondingLockId = del.nextUnbondingLockId; // Create new unbonding lock del.unbondingLocks[unbondingLockId] = UnbondingLock({ amount: _amount, withdrawRound: withdrawRound }); // Increment ID for next unbonding lock del.nextUnbondingLockId = unbondingLockId.add(1); // Decrease delegator's bonded amount del.bondedAmount = del.bondedAmount.sub(_amount); if (del.bondedAmount == 0) { // Delegator no longer delegated to anyone if it does not have a bonded amount del.delegateAddress = address(0); // Delegator does not have a start round if it is no longer delegated to anyone del.startRound = 0; if (transcoderPool.contains(msg.sender)) { resignTranscoder(msg.sender); } } // If msg.sender was resigned this statement will only decrease delegators[currentDelegate].delegatedAmount decreaseTotalStake(currentDelegate, _amount, _newPosPrev, _newPosNext); emit Unbond(currentDelegate, msg.sender, unbondingLockId, _amount, withdrawRound); } /** * @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status and updates * the transcoder pool using an optional list hint if needed * @dev If the delegate is in the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the * pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position. * In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints * @param _unbondingLockId ID of unbonding lock to rebond with * @param _newPosPrev Address of previous transcoder in pool if the delegate is in the pool * @param _newPosNext Address of next transcoder in pool if the delegate is in the pool */ function rebondWithHint( uint256 _unbondingLockId, address _newPosPrev, address _newPosNext ) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings { require(delegatorStatus(msg.sender) != DelegatorStatus.Unbonded, "caller must be bonded"); // Process rebond using unbonding lock processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext); } /** * @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status and updates the transcoder pool using * an optional list hint if needed * @dev If the delegate joins the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the * pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position. * In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints * @param _to Address of delegate * @param _unbondingLockId ID of unbonding lock to rebond with * @param _newPosPrev Address of previous transcoder in pool if the delegate joins the pool * @param _newPosNext Address of next transcoder in pool if the delegate joins the pool */ function rebondFromUnbondedWithHint( address _to, uint256 _unbondingLockId, address _newPosPrev, address _newPosNext ) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings { require(delegatorStatus(msg.sender) == DelegatorStatus.Unbonded, "caller must be unbonded"); // Set delegator's start round and transition into Pending state delegators[msg.sender].startRound = roundsManager().currentRound().add(1); // Set delegator's delegate delegators[msg.sender].delegateAddress = _to; // Process rebond using unbonding lock processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext); } /** * @notice Mint token rewards for an active transcoder and its delegators and update the transcoder pool using an optional list hint if needed * @dev If the caller is in the transcoder pool, the caller can provide an optional hint for its insertion position in the * pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position. * In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints * @param _newPosPrev Address of previous transcoder in pool if the caller is in the pool * @param _newPosNext Address of next transcoder in pool if the caller is in the pool */ function rewardWithHint(address _newPosPrev, address _newPosNext) public whenSystemNotPaused currentRoundInitialized { uint256 currentRound = roundsManager().currentRound(); require(isActiveTranscoder(msg.sender), "caller must be an active transcoder"); require( transcoders[msg.sender].lastRewardRound != currentRound, "caller has already called reward for the current round" ); Transcoder storage t = transcoders[msg.sender]; EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound]; // Set last round that transcoder called reward earningsPool.setCommission(t.rewardCut, t.feeShare); // If transcoder didn't receive stake updates during the previous round and hasn't called reward for > 1 round // the 'totalStake' on its 'EarningsPool' for the current round wouldn't be initialized // Thus we sync the the transcoder's stake to when it was last updated // 'updateTrancoderWithRewards()' will set the update round to 'currentRound +1' so this synchronization shouldn't occur frequently uint256 lastUpdateRound = t.lastActiveStakeUpdateRound; if (lastUpdateRound < currentRound) { earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake); } // Create reward based on active transcoder's stake relative to the total active stake // rewardTokens = (current mintable tokens for the round * active transcoder stake) / total active stake uint256 rewardTokens = minter().createReward(earningsPool.totalStake, currentRoundTotalActiveStake); updateTranscoderWithRewards(msg.sender, rewardTokens, currentRound, _newPosPrev, _newPosNext); // Set last round that transcoder called reward t.lastRewardRound = currentRound; emit Reward(msg.sender, rewardTokens); } /** * @notice Returns pending bonded stake for a delegator from its lastClaimRound through an end round * @param _delegator Address of delegator * @param _endRound The last round to compute pending stake from * @return Pending bonded stake for '_delegator' since last claiming rewards */ function pendingStake(address _delegator, uint256 _endRound) public view returns (uint256) { // Silence unused param compiler warning _endRound; uint256 endRound = roundsManager().currentRound(); (uint256 stake, ) = pendingStakeAndFees(_delegator, endRound); return stake; } /** * @notice Returns pending fees for a delegator from its lastClaimRound through an end round * @param _delegator Address of delegator * @param _endRound The last round to compute pending fees from * @return Pending fees for '_delegator' since last claiming fees */ function pendingFees(address _delegator, uint256 _endRound) public view returns (uint256) { // Silence unused param compiler warning _endRound; uint256 endRound = roundsManager().currentRound(); (, uint256 fees) = pendingStakeAndFees(_delegator, endRound); return fees; } /** * @notice Returns total bonded stake for a transcoder * @param _transcoder Address of transcoder * @return total bonded stake for a delegator */ function transcoderTotalStake(address _transcoder) public view returns (uint256) { return delegators[_transcoder].delegatedAmount; } /** * @notice Computes transcoder status * @param _transcoder Address of transcoder * @return registered or not registered transcoder status */ function transcoderStatus(address _transcoder) public view returns (TranscoderStatus) { if (isRegisteredTranscoder(_transcoder)) return TranscoderStatus.Registered; return TranscoderStatus.NotRegistered; } /** * @notice Computes delegator status * @param _delegator Address of delegator * @return bonded, unbonded or pending delegator status */ function delegatorStatus(address _delegator) public view returns (DelegatorStatus) { Delegator storage del = delegators[_delegator]; if (del.bondedAmount == 0) { // Delegator unbonded all its tokens return DelegatorStatus.Unbonded; } else if (del.startRound > roundsManager().currentRound()) { // Delegator round start is in the future return DelegatorStatus.Pending; } else { // Delegator round start is now or in the past // del.startRound != 0 here because if del.startRound = 0 then del.bondedAmount = 0 which // would trigger the first if clause return DelegatorStatus.Bonded; } } /** * @notice Return transcoder information * @param _transcoder Address of transcoder * @return lastRewardRound Trancoder's last reward round * @return rewardCut Transcoder's reward cut * @return feeShare Transcoder's fee share * @return lastActiveStakeUpdateRound Round in which transcoder's stake was last updated while active * @return activationRound Round in which transcoder became active * @return deactivationRound Round in which transcoder will no longer be active * @return activeCumulativeRewards Transcoder's cumulative rewards that are currently active * @return cumulativeRewards Transcoder's cumulative rewards (earned via its active staked rewards and its reward cut) * @return cumulativeFees Transcoder's cumulative fees (earned via its active staked rewards and its fee share) * @return lastFeeRound Latest round that the transcoder received fees */ function getTranscoder(address _transcoder) public view returns ( uint256 lastRewardRound, uint256 rewardCut, uint256 feeShare, uint256 lastActiveStakeUpdateRound, uint256 activationRound, uint256 deactivationRound, uint256 activeCumulativeRewards, uint256 cumulativeRewards, uint256 cumulativeFees, uint256 lastFeeRound ) { Transcoder storage t = transcoders[_transcoder]; lastRewardRound = t.lastRewardRound; rewardCut = t.rewardCut; feeShare = t.feeShare; lastActiveStakeUpdateRound = t.lastActiveStakeUpdateRound; activationRound = t.activationRound; deactivationRound = t.deactivationRound; activeCumulativeRewards = t.activeCumulativeRewards; cumulativeRewards = t.cumulativeRewards; cumulativeFees = t.cumulativeFees; lastFeeRound = t.lastFeeRound; } /** * @notice Return transcoder's earnings pool for a given round * @param _transcoder Address of transcoder * @param _round Round number * @return totalStake Transcoder's total stake in '_round' * @return transcoderRewardCut Transcoder's reward cut for '_round' * @return transcoderFeeShare Transcoder's fee share for '_round' * @return cumulativeRewardFactor The cumulative reward factor for delegator rewards calculation (only used after LIP-36) * @return cumulativeFeeFactor The cumulative fee factor for delegator fees calculation (only used after LIP-36) */ function getTranscoderEarningsPoolForRound(address _transcoder, uint256 _round) public view returns ( uint256 totalStake, uint256 transcoderRewardCut, uint256 transcoderFeeShare, uint256 cumulativeRewardFactor, uint256 cumulativeFeeFactor ) { EarningsPool.Data storage earningsPool = transcoders[_transcoder].earningsPoolPerRound[_round]; totalStake = earningsPool.totalStake; transcoderRewardCut = earningsPool.transcoderRewardCut; transcoderFeeShare = earningsPool.transcoderFeeShare; cumulativeRewardFactor = earningsPool.cumulativeRewardFactor; cumulativeFeeFactor = earningsPool.cumulativeFeeFactor; } /** * @notice Return delegator info * @param _delegator Address of delegator * @return bondedAmount total amount bonded by '_delegator' * @return fees amount of fees collected by '_delegator' * @return delegateAddress address '_delegator' has bonded to * @return delegatedAmount total amount delegated to '_delegator' * @return startRound round in which bond for '_delegator' became effective * @return lastClaimRound round for which '_delegator' has last claimed earnings * @return nextUnbondingLockId ID for the next unbonding lock created for '_delegator' */ function getDelegator(address _delegator) public view returns ( uint256 bondedAmount, uint256 fees, address delegateAddress, uint256 delegatedAmount, uint256 startRound, uint256 lastClaimRound, uint256 nextUnbondingLockId ) { Delegator storage del = delegators[_delegator]; bondedAmount = del.bondedAmount; fees = del.fees; delegateAddress = del.delegateAddress; delegatedAmount = del.delegatedAmount; startRound = del.startRound; lastClaimRound = del.lastClaimRound; nextUnbondingLockId = del.nextUnbondingLockId; } /** * @notice Return delegator's unbonding lock info * @param _delegator Address of delegator * @param _unbondingLockId ID of unbonding lock * @return amount of stake locked up by unbonding lock * @return withdrawRound round in which 'amount' becomes available for withdrawal */ function getDelegatorUnbondingLock(address _delegator, uint256 _unbondingLockId) public view returns (uint256 amount, uint256 withdrawRound) { UnbondingLock storage lock = delegators[_delegator].unbondingLocks[_unbondingLockId]; return (lock.amount, lock.withdrawRound); } /** * @notice Returns max size of transcoder pool * @return transcoder pool max size */ function getTranscoderPoolMaxSize() public view returns (uint256) { return transcoderPool.getMaxSize(); } /** * @notice Returns size of transcoder pool * @return transcoder pool current size */ function getTranscoderPoolSize() public view returns (uint256) { return transcoderPool.getSize(); } /** * @notice Returns transcoder with most stake in pool * @return address for transcoder with highest stake in transcoder pool */ function getFirstTranscoderInPool() public view returns (address) { return transcoderPool.getFirst(); } /** * @notice Returns next transcoder in pool for a given transcoder * @param _transcoder Address of a transcoder in the pool * @return address for the transcoder after '_transcoder' in transcoder pool */ function getNextTranscoderInPool(address _transcoder) public view returns (address) { return transcoderPool.getNext(_transcoder); } /** * @notice Return total bonded tokens * @return total active stake for the current round */ function getTotalBonded() public view returns (uint256) { return currentRoundTotalActiveStake; } /** * @notice Return whether a transcoder is active for the current round * @param _transcoder Transcoder address * @return true if transcoder is active */ function isActiveTranscoder(address _transcoder) public view returns (bool) { Transcoder storage t = transcoders[_transcoder]; uint256 currentRound = roundsManager().currentRound(); return t.activationRound <= currentRound && currentRound < t.deactivationRound; } /** * @notice Return whether a transcoder is registered * @param _transcoder Transcoder address * @return true if transcoder is self-bonded */ function isRegisteredTranscoder(address _transcoder) public view returns (bool) { Delegator storage d = delegators[_transcoder]; return d.delegateAddress == _transcoder && d.bondedAmount > 0; } /** * @notice Return whether an unbonding lock for a delegator is valid * @param _delegator Address of delegator * @param _unbondingLockId ID of unbonding lock * @return true if unbondingLock for ID has a non-zero withdraw round */ function isValidUnbondingLock(address _delegator, uint256 _unbondingLockId) public view returns (bool) { // A unbonding lock is only valid if it has a non-zero withdraw round (the default value is zero) return delegators[_delegator].unbondingLocks[_unbondingLockId].withdrawRound > 0; } /** * @notice Return an EarningsPool.Data struct with cumulative factors for a given round that are rescaled if needed * @param _transcoder Storage pointer to a transcoder struct * @param _round The round to fetch the cumulative factors for */ function cumulativeFactorsPool(Transcoder storage _transcoder, uint256 _round) internal view returns (EarningsPool.Data memory pool) { pool.cumulativeRewardFactor = _transcoder.earningsPoolPerRound[_round].cumulativeRewardFactor; pool.cumulativeFeeFactor = _transcoder.earningsPoolPerRound[_round].cumulativeFeeFactor; return pool; } /** * @notice Return an EarningsPool.Data struct with the latest cumulative factors for a given round * @param _transcoder Storage pointer to a transcoder struct * @param _round The round to fetch the latest cumulative factors for * @return pool An EarningsPool.Data populated with the latest cumulative factors for _round */ function latestCumulativeFactorsPool(Transcoder storage _transcoder, uint256 _round) internal view returns (EarningsPool.Data memory pool) { pool = cumulativeFactorsPool(_transcoder, _round); uint256 lastRewardRound = _transcoder.lastRewardRound; // Only use the cumulativeRewardFactor for lastRewardRound if lastRewardRound is before _round if (pool.cumulativeRewardFactor == 0 && lastRewardRound < _round) { pool.cumulativeRewardFactor = cumulativeFactorsPool(_transcoder, lastRewardRound).cumulativeRewardFactor; } uint256 lastFeeRound = _transcoder.lastFeeRound; // Only use the cumulativeFeeFactor for lastFeeRound if lastFeeRound is before _round if (pool.cumulativeFeeFactor == 0 && lastFeeRound < _round) { pool.cumulativeFeeFactor = cumulativeFactorsPool(_transcoder, lastFeeRound).cumulativeFeeFactor; } return pool; } /** * @notice Return a delegator's cumulative stake and fees using the LIP-36 earnings claiming algorithm * @param _transcoder Storage pointer to a transcoder struct for a delegator's delegate * @param _startRound The round for the start cumulative factors * @param _endRound The round for the end cumulative factors * @param _stake The delegator's initial stake before including earned rewards * @param _fees The delegator's initial fees before including earned fees * @return cStake , cFees where cStake is the delegator's cumulative stake including earned rewards and cFees is the delegator's cumulative fees including earned fees */ function delegatorCumulativeStakeAndFees( Transcoder storage _transcoder, uint256 _startRound, uint256 _endRound, uint256 _stake, uint256 _fees ) internal view returns (uint256 cStake, uint256 cFees) { // Fetch start cumulative factors EarningsPool.Data memory startPool = cumulativeFactorsPool(_transcoder, _startRound); // If the start cumulativeRewardFactor is 0 set the default value to PreciseMathUtils.percPoints(1, 1) if (startPool.cumulativeRewardFactor == 0) { startPool.cumulativeRewardFactor = PreciseMathUtils.percPoints(1, 1); } // Fetch end cumulative factors EarningsPool.Data memory endPool = latestCumulativeFactorsPool(_transcoder, _endRound); // If the end cumulativeRewardFactor is 0 set the default value to PreciseMathUtils.percPoints(1, 1) if (endPool.cumulativeRewardFactor == 0) { endPool.cumulativeRewardFactor = PreciseMathUtils.percPoints(1, 1); } cFees = _fees.add( PreciseMathUtils.percOf( _stake, endPool.cumulativeFeeFactor.sub(startPool.cumulativeFeeFactor), startPool.cumulativeRewardFactor ) ); cStake = PreciseMathUtils.percOf(_stake, endPool.cumulativeRewardFactor, startPool.cumulativeRewardFactor); return (cStake, cFees); } /** * @notice Return the pending stake and fees for a delegator * @param _delegator Address of a delegator * @param _endRound The last round to claim earnings for when calculating the pending stake and fees * @return stake , fees where stake is the delegator's pending stake and fees is the delegator's pending fees */ function pendingStakeAndFees(address _delegator, uint256 _endRound) internal view returns (uint256 stake, uint256 fees) { Delegator storage del = delegators[_delegator]; Transcoder storage t = transcoders[del.delegateAddress]; fees = del.fees; stake = del.bondedAmount; uint256 startRound = del.lastClaimRound.add(1); address delegateAddr = del.delegateAddress; bool isTranscoder = _delegator == delegateAddr; // Make sure there is a round to claim i.e. end round - (start round - 1) > 0 if (startRound <= _endRound) { (stake, fees) = delegatorCumulativeStakeAndFees(t, startRound.sub(1), _endRound, stake, fees); } // cumulativeRewards and cumulativeFees will track *all* rewards/fees earned by the transcoder // so it is important that this is only executed with the end round as the current round or else // the returned stake and fees will reflect rewards/fees earned in the future relative to the end round if (isTranscoder) { stake = stake.add(t.cumulativeRewards); fees = fees.add(t.cumulativeFees); } return (stake, fees); } /** * @dev Increase the total stake for a delegate and updates its 'lastActiveStakeUpdateRound' * @param _delegate The delegate to increase the stake for * @param _amount The amount to increase the stake for '_delegate' by */ function increaseTotalStake( address _delegate, uint256 _amount, address _newPosPrev, address _newPosNext ) internal { if (isRegisteredTranscoder(_delegate)) { uint256 currStake = transcoderTotalStake(_delegate); uint256 newStake = currStake.add(_amount); uint256 currRound = roundsManager().currentRound(); uint256 nextRound = currRound.add(1); // If the transcoder is already in the active set update its stake and return if (transcoderPool.contains(_delegate)) { transcoderPool.updateKey(_delegate, newStake, _newPosPrev, _newPosNext); nextRoundTotalActiveStake = nextRoundTotalActiveStake.add(_amount); Transcoder storage t = transcoders[_delegate]; // currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound // because it is updated every time lastActiveStakeUpdateRound is updated // The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards() // and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound if (t.lastActiveStakeUpdateRound < currRound) { t.earningsPoolPerRound[currRound].setStake(currStake); } t.earningsPoolPerRound[nextRound].setStake(newStake); t.lastActiveStakeUpdateRound = nextRound; } else { // Check if the transcoder is eligible to join the active set in the update round tryToJoinActiveSet(_delegate, newStake, nextRound, _newPosPrev, _newPosNext); } } // Increase delegate's delegated amount delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.add(_amount); } /** * @dev Decrease the total stake for a delegate and updates its 'lastActiveStakeUpdateRound' * @param _delegate The transcoder to decrease the stake for * @param _amount The amount to decrease the stake for '_delegate' by */ function decreaseTotalStake( address _delegate, uint256 _amount, address _newPosPrev, address _newPosNext ) internal { if (transcoderPool.contains(_delegate)) { uint256 currStake = transcoderTotalStake(_delegate); uint256 newStake = currStake.sub(_amount); uint256 currRound = roundsManager().currentRound(); uint256 nextRound = currRound.add(1); transcoderPool.updateKey(_delegate, newStake, _newPosPrev, _newPosNext); nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(_amount); Transcoder storage t = transcoders[_delegate]; // currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound // because it is updated every time lastActiveStakeUpdateRound is updated // The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards() // and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound if (t.lastActiveStakeUpdateRound < currRound) { t.earningsPoolPerRound[currRound].setStake(currStake); } t.lastActiveStakeUpdateRound = nextRound; t.earningsPoolPerRound[nextRound].setStake(newStake); } // Decrease old delegate's delegated amount delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.sub(_amount); } /** * @dev Tries to add a transcoder to active transcoder pool, evicts the active transcoder with the lowest stake if the pool is full * @param _transcoder The transcoder to insert into the transcoder pool * @param _totalStake The total stake for '_transcoder' * @param _activationRound The round in which the transcoder should become active */ function tryToJoinActiveSet( address _transcoder, uint256 _totalStake, uint256 _activationRound, address _newPosPrev, address _newPosNext ) internal { uint256 pendingNextRoundTotalActiveStake = nextRoundTotalActiveStake; if (transcoderPool.isFull()) { address lastTranscoder = transcoderPool.getLast(); uint256 lastStake = transcoderTotalStake(lastTranscoder); // If the pool is full and the transcoder has less stake than the least stake transcoder in the pool // then the transcoder is unable to join the active set for the next round if (_totalStake <= lastStake) { return; } // Evict the least stake transcoder from the active set for the next round // Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted) // There should be no side-effects as long as the value is properly updated on stake updates // Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as // 'EarningsPool.setStake()' is called whenever a transcoder becomes active again. transcoderPool.remove(lastTranscoder); transcoders[lastTranscoder].deactivationRound = _activationRound; pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.sub(lastStake); emit TranscoderDeactivated(lastTranscoder, _activationRound); } transcoderPool.insert(_transcoder, _totalStake, _newPosPrev, _newPosNext); pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.add(_totalStake); Transcoder storage t = transcoders[_transcoder]; t.lastActiveStakeUpdateRound = _activationRound; t.activationRound = _activationRound; t.deactivationRound = MAX_FUTURE_ROUND; t.earningsPoolPerRound[_activationRound].setStake(_totalStake); nextRoundTotalActiveStake = pendingNextRoundTotalActiveStake; emit TranscoderActivated(_transcoder, _activationRound); } /** * @dev Remove a transcoder from the pool and deactivate it */ function resignTranscoder(address _transcoder) internal { // Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted) // There should be no side-effects as long as the value is properly updated on stake updates // Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as // 'EarningsPool.setStake()' is called whenever a transcoder becomes active again. transcoderPool.remove(_transcoder); nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(transcoderTotalStake(_transcoder)); uint256 deactivationRound = roundsManager().currentRound().add(1); transcoders[_transcoder].deactivationRound = deactivationRound; emit TranscoderDeactivated(_transcoder, deactivationRound); } /** * @dev Update a transcoder with rewards and update the transcoder pool with an optional list hint if needed. * See SortedDoublyLL.sol for details on list hints * @param _transcoder Address of transcoder * @param _rewards Amount of rewards * @param _round Round that transcoder is updated * @param _newPosPrev Address of previous transcoder in pool if the transcoder is in the pool * @param _newPosNext Address of next transcoder in pool if the transcoder is in the pool */ function updateTranscoderWithRewards( address _transcoder, uint256 _rewards, uint256 _round, address _newPosPrev, address _newPosNext ) internal { Transcoder storage t = transcoders[_transcoder]; EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[_round]; EarningsPool.Data memory prevEarningsPool = cumulativeFactorsPool(t, t.lastRewardRound); t.activeCumulativeRewards = t.cumulativeRewards; uint256 transcoderCommissionRewards = MathUtils.percOf(_rewards, earningsPool.transcoderRewardCut); uint256 delegatorsRewards = _rewards.sub(transcoderCommissionRewards); // Calculate the rewards earned by the transcoder's earned rewards uint256 transcoderRewardStakeRewards = PreciseMathUtils.percOf( delegatorsRewards, t.activeCumulativeRewards, earningsPool.totalStake ); // Track rewards earned by the transcoder based on its earned rewards and rewardCut t.cumulativeRewards = t.cumulativeRewards.add(transcoderRewardStakeRewards).add(transcoderCommissionRewards); // Update cumulative reward factor with new rewards // The cumulativeRewardFactor is used to calculate rewards for all delegators including the transcoder (self-delegated) // Note that delegatorsRewards includes transcoderRewardStakeRewards, but no delegator will claim that amount using // the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeRewards field earningsPool.updateCumulativeRewardFactor(prevEarningsPool, delegatorsRewards); // Update transcoder's total stake with rewards increaseTotalStake(_transcoder, _rewards, _newPosPrev, _newPosNext); } /** * @dev Update a delegator with token pools shares from its lastClaimRound through a given round * @param _delegator Delegator address * @param _endRound The last round for which to update a delegator's stake with earnings pool shares * @param _lastClaimRound The round for which a delegator has last claimed earnings */ function updateDelegatorWithEarnings( address _delegator, uint256 _endRound, uint256 _lastClaimRound ) internal { Delegator storage del = delegators[_delegator]; uint256 startRound = _lastClaimRound.add(1); uint256 currentBondedAmount = del.bondedAmount; uint256 currentFees = del.fees; // Only will have earnings to claim if you have a delegate // If not delegated, skip the earnings claim process if (del.delegateAddress != address(0)) { (currentBondedAmount, currentFees) = pendingStakeAndFees(_delegator, _endRound); // Check whether the endEarningsPool is initialised // If it is not initialised set it's cumulative factors so that they can be used when a delegator // next claims earnings as the start cumulative factors (see delegatorCumulativeStakeAndFees()) Transcoder storage t = transcoders[del.delegateAddress]; EarningsPool.Data storage endEarningsPool = t.earningsPoolPerRound[_endRound]; if (endEarningsPool.cumulativeRewardFactor == 0) { uint256 lastRewardRound = t.lastRewardRound; if (lastRewardRound < _endRound) { endEarningsPool.cumulativeRewardFactor = cumulativeFactorsPool(t, lastRewardRound) .cumulativeRewardFactor; } } if (endEarningsPool.cumulativeFeeFactor == 0) { uint256 lastFeeRound = t.lastFeeRound; if (lastFeeRound < _endRound) { endEarningsPool.cumulativeFeeFactor = cumulativeFactorsPool(t, lastFeeRound).cumulativeFeeFactor; } } if (del.delegateAddress == _delegator) { t.cumulativeFees = 0; t.cumulativeRewards = 0; // activeCumulativeRewards is not cleared here because the next reward() call will set it to cumulativeRewards } } emit EarningsClaimed( del.delegateAddress, _delegator, currentBondedAmount.sub(del.bondedAmount), currentFees.sub(del.fees), startRound, _endRound ); del.lastClaimRound = _endRound; // Rewards are bonded by default del.bondedAmount = currentBondedAmount; del.fees = currentFees; } /** * @dev Update the state of a delegator and its delegate by processing a rebond using an unbonding lock and update the transcoder pool with an optional * list hint if needed. See SortedDoublyLL.sol for details on list hints * @param _delegator Address of delegator * @param _unbondingLockId ID of unbonding lock to rebond with * @param _newPosPrev Address of previous transcoder in pool if the delegate is already in or joins the pool * @param _newPosNext Address of next transcoder in pool if the delegate is already in or joins the pool */ function processRebond( address _delegator, uint256 _unbondingLockId, address _newPosPrev, address _newPosNext ) internal { Delegator storage del = delegators[_delegator]; UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId]; require(isValidUnbondingLock(_delegator, _unbondingLockId), "invalid unbonding lock ID"); uint256 amount = lock.amount; // Increase delegator's bonded amount del.bondedAmount = del.bondedAmount.add(amount); // Delete lock delete del.unbondingLocks[_unbondingLockId]; increaseTotalStake(del.delegateAddress, amount, _newPosPrev, _newPosNext); emit Rebond(del.delegateAddress, _delegator, _unbondingLockId, amount); } /** * @dev Return LivepeerToken interface * @return Livepeer token contract registered with Controller */ function livepeerToken() internal view returns (ILivepeerToken) { return ILivepeerToken(controller.getContract(keccak256("LivepeerToken"))); } /** * @dev Return Minter interface * @return Minter contract registered with Controller */ function minter() internal view returns (IMinter) { return IMinter(controller.getContract(keccak256("Minter"))); } /** * @dev Return RoundsManager interface * @return RoundsManager contract registered with Controller */ function roundsManager() internal view returns (IRoundsManager) { return IRoundsManager(controller.getContract(keccak256("RoundsManager"))); } function _onlyTicketBroker() internal view { require(msg.sender == controller.getContract(keccak256("TicketBroker")), "caller must be TicketBroker"); } function _onlyRoundsManager() internal view { require(msg.sender == controller.getContract(keccak256("RoundsManager")), "caller must be RoundsManager"); } function _onlyVerifier() internal view { require(msg.sender == controller.getContract(keccak256("Verifier")), "caller must be Verifier"); } function _currentRoundInitialized() internal view { require(roundsManager().currentRoundInitialized(), "current round is not initialized"); } function _autoClaimEarnings() internal { uint256 currentRound = roundsManager().currentRound(); uint256 lastClaimRound = delegators[msg.sender].lastClaimRound; if (lastClaimRound < currentRound) { updateDelegatorWithEarnings(msg.sender, currentRound, lastClaimRound); } } }
* @notice Mint token rewards for an active transcoder and its delegators and update the transcoder pool using an optional list hint if needed @dev If the caller is in the transcoder pool, the caller can provide an optional hint for its insertion position in the pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position. In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints @param _newPosPrev Address of previous transcoder in pool if the caller is in the pool @param _newPosNext Address of next transcoder in pool if the caller is in the pool/ Set last round that transcoder called reward If transcoder didn't receive stake updates during the previous round and hasn't called reward for > 1 round the 'totalStake' on its 'EarningsPool' for the current round wouldn't be initialized Thus we sync the the transcoder's stake to when it was last updated 'updateTrancoderWithRewards()' will set the update round to 'currentRound +1' so this synchronization shouldn't occur frequently
function rewardWithHint(address _newPosPrev, address _newPosNext) public whenSystemNotPaused currentRoundInitialized { uint256 currentRound = roundsManager().currentRound(); require(isActiveTranscoder(msg.sender), "caller must be an active transcoder"); require( transcoders[msg.sender].lastRewardRound != currentRound, "caller has already called reward for the current round" ); Transcoder storage t = transcoders[msg.sender]; EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound]; earningsPool.setCommission(t.rewardCut, t.feeShare); uint256 lastUpdateRound = t.lastActiveStakeUpdateRound; if (lastUpdateRound < currentRound) { earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake); } updateTranscoderWithRewards(msg.sender, rewardTokens, currentRound, _newPosPrev, _newPosNext); emit Reward(msg.sender, rewardTokens); }
13,004,556
[ 1, 49, 474, 1147, 283, 6397, 364, 392, 2695, 906, 3396, 471, 2097, 11158, 3062, 471, 1089, 326, 906, 3396, 2845, 1450, 392, 3129, 666, 7380, 309, 3577, 225, 971, 326, 4894, 353, 316, 326, 906, 3396, 2845, 16, 326, 4894, 848, 5615, 392, 3129, 7380, 364, 2097, 12626, 1754, 316, 326, 2845, 3970, 326, 1375, 67, 2704, 1616, 9958, 68, 471, 1375, 67, 2704, 1616, 2134, 68, 859, 18, 432, 9103, 1623, 903, 506, 7120, 5023, 622, 326, 7380, 358, 1104, 326, 3434, 1754, 18, 657, 326, 3796, 648, 16, 326, 7380, 353, 326, 3434, 1754, 1427, 1158, 1623, 353, 7120, 18, 2164, 13717, 3244, 440, 93, 4503, 18, 18281, 364, 3189, 603, 666, 13442, 225, 389, 2704, 1616, 9958, 5267, 434, 2416, 906, 3396, 316, 2845, 309, 326, 4894, 353, 316, 326, 2845, 225, 389, 2704, 1616, 2134, 5267, 434, 1024, 906, 3396, 316, 2845, 309, 326, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 19890, 1190, 7002, 12, 2867, 389, 2704, 1616, 9958, 16, 1758, 389, 2704, 1616, 2134, 13, 203, 3639, 1071, 203, 3639, 1347, 3163, 1248, 28590, 203, 3639, 783, 11066, 11459, 203, 565, 288, 203, 3639, 2254, 5034, 783, 11066, 273, 21196, 1318, 7675, 2972, 11066, 5621, 203, 203, 3639, 2583, 12, 291, 3896, 1429, 3396, 12, 3576, 18, 15330, 3631, 315, 16140, 1297, 506, 392, 2695, 906, 3396, 8863, 203, 3639, 2583, 12, 203, 5411, 906, 1559, 414, 63, 3576, 18, 15330, 8009, 2722, 17631, 1060, 11066, 480, 783, 11066, 16, 203, 5411, 315, 16140, 711, 1818, 2566, 19890, 364, 326, 783, 3643, 6, 203, 3639, 11272, 203, 203, 3639, 2604, 3396, 2502, 268, 273, 906, 1559, 414, 63, 3576, 18, 15330, 15533, 203, 3639, 512, 1303, 899, 2864, 18, 751, 2502, 425, 1303, 899, 2864, 273, 268, 18, 73, 1303, 899, 2864, 2173, 11066, 63, 2972, 11066, 15533, 203, 203, 3639, 425, 1303, 899, 2864, 18, 542, 799, 3951, 12, 88, 18, 266, 2913, 15812, 16, 268, 18, 21386, 9535, 1769, 203, 203, 3639, 2254, 5034, 1142, 1891, 11066, 273, 268, 18, 2722, 3896, 510, 911, 1891, 11066, 31, 203, 3639, 309, 261, 2722, 1891, 11066, 411, 783, 11066, 13, 288, 203, 5411, 425, 1303, 899, 2864, 18, 542, 510, 911, 12, 88, 18, 73, 1303, 899, 2864, 2173, 11066, 63, 2722, 1891, 11066, 8009, 4963, 510, 911, 1769, 203, 3639, 289, 203, 203, 203, 3639, 1089, 1429, 3396, 1190, 17631, 14727, 12, 3576, 18, 15330, 16, 19890, 5157, 16, 783, 2 ]
./full_match/1/0x5E16CA75000fb2B9d7B1184Fa24fF5D938a345Ef/sources/lib/chronicle-std/src/toll/Toll.sol
@dev Mapping storing whether address is tolled. @custom:invariant Image of mapping is {0, 1}. ∀x ∊ Address: _buds[x] ∊ {0, 1} @custom:invariant Only functions `kiss` and `diss` may mutate the mapping's state. ∀x ∊ Address: preTx(_buds[x]) != postTx(_buds[x]) → (msg.sig == "kiss" ∨ msg.sig == "diss") @custom:invariant Mapping's state may only be mutated by authenticated caller. ∀x ∊ Address: preTx(_buds[x]) != postTx(_buds[x]) → toll_auth() @dev List of addresses possibly being tolled. @dev May contain duplicates. @dev May contain addresses not being tolled anymore. @custom:invariant Every address being tolled once is element of the list. ∀x ∊ Address: tolled(x) → x ∊ _budsTouched @dev Ensures caller is tolled. Compute slot of _buds[msg.sender]. Revert if caller not tolled. Store selector of `NotTolled(address)`. Store msg.sender. Revert with (offset, size).
modifier toll() { assembly ("memory-safe") { mstore(0x00, caller()) mstore(0x20, _buds.slot) let slot := keccak256(0x00, 0x40) let isTolled := sload(slot) if iszero(isTolled) { mstore(0x00, 0xd957b595) mstore(0x20, caller()) revert(0x1c, 0x24) } } _; }
17,127,032
[ 1, 3233, 15729, 2856, 1758, 353, 6085, 1259, 18, 632, 3662, 30, 267, 8688, 3421, 434, 2874, 353, 288, 20, 16, 404, 5496, 5397, 225, 163, 235, 227, 92, 225, 163, 235, 237, 5267, 30, 389, 70, 1100, 87, 63, 92, 65, 225, 163, 235, 237, 288, 20, 16, 404, 97, 632, 3662, 30, 267, 8688, 5098, 4186, 1375, 79, 1054, 68, 471, 1375, 72, 1054, 68, 2026, 15887, 326, 2874, 1807, 919, 18, 5397, 225, 163, 235, 227, 92, 225, 163, 235, 237, 5267, 30, 675, 4188, 24899, 70, 1100, 87, 63, 92, 5717, 480, 1603, 4188, 24899, 70, 1100, 87, 63, 92, 5717, 19694, 225, 163, 233, 245, 261, 3576, 18, 7340, 422, 315, 79, 1054, 6, 225, 163, 235, 106, 1234, 18, 7340, 422, 315, 72, 1054, 7923, 632, 3662, 30, 267, 8688, 9408, 1807, 919, 2026, 1338, 506, 27414, 635, 9370, 4894, 18, 5397, 225, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 9606, 6085, 80, 1435, 288, 203, 3639, 19931, 7566, 7858, 17, 4626, 7923, 288, 203, 5411, 312, 2233, 12, 20, 92, 713, 16, 4894, 10756, 203, 5411, 312, 2233, 12, 20, 92, 3462, 16, 389, 70, 1100, 87, 18, 14194, 13, 203, 5411, 2231, 4694, 519, 417, 24410, 581, 5034, 12, 20, 92, 713, 16, 374, 92, 7132, 13, 203, 203, 5411, 2231, 353, 16557, 1259, 519, 272, 945, 12, 14194, 13, 203, 5411, 309, 353, 7124, 12, 291, 16557, 1259, 13, 288, 203, 7734, 312, 2233, 12, 20, 92, 713, 16, 374, 7669, 8778, 27, 70, 6162, 25, 13, 203, 7734, 312, 2233, 12, 20, 92, 3462, 16, 4894, 10756, 203, 7734, 15226, 12, 20, 92, 21, 71, 16, 374, 92, 3247, 13, 203, 5411, 289, 203, 3639, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @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; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor(address sender) public { if (!isMinter(sender)) { _addMinter(sender); } } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } /** * @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 Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual 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 virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @title Standard ERC20 token, with minting and burn functionality. * */ contract ShakeERC20 is ERC20, MinterRole { uint256 public immutable MAX_TOTAL_SUPPLY; uint256 public totalMinted = 0; uint256 public totalBurned = 0; constructor( //string memory name, string memory symbol ) public ERC20('SHAKE token by SpaceSwap v2', 'SHAKE') MinterRole(address(msg.sender)) { MAX_TOTAL_SUPPLY = 10000*10**18; //10 000 SHAKE } /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter returns (bool) { require(totalSupply().add(value) <= MAX_TOTAL_SUPPLY, "Can`t mint more than MAX_TOTAL_SUPPLY"); _mint(to, value); totalMinted = totalMinted.add(value); return true; } /** * @dev Function to burn tokens * @param to The address that tokens will burn. * @param value The amount of tokens to burn. * @return A boolean that indicates if the operation was successful. */ function burn(address to, uint256 value) public onlyMinter returns (bool) { _burn(to, value); totalBurned = totalBurned.add(value); return true; } /** * @dev Minter can claim any tokens that transfered to this contract address */ function reclaimToken(ERC20 token) external onlyMinter { require(address(token) != address(0)); uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } }
* @title Standard ERC20 token @dev Implementation of the basic standard token. Originally based on code by FirstBlood: 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 _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 name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
2,208,213
[ 1, 8336, 4232, 39, 3462, 1147, 225, 25379, 434, 326, 5337, 4529, 1147, 18, 18040, 1230, 2511, 603, 981, 635, 5783, 38, 383, 369, 30, 1220, 4471, 24169, 3312, 1716, 685, 1125, 2641, 16, 15632, 12165, 358, 23243, 326, 1699, 1359, 1267, 364, 777, 9484, 2537, 635, 13895, 358, 7864, 350, 2641, 18, 3609, 716, 333, 5177, 1404, 1931, 635, 326, 7490, 16, 471, 1308, 24820, 16164, 2026, 486, 741, 518, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3462, 353, 225, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 203, 97, 203, 565, 3885, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 3639, 389, 31734, 273, 6549, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 70, 26488, 63, 4631, 15533, 2 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/access/Ownable.sol"; //import "@openzeppelin/contracts/utils/Context.sol"; import "https://github.com/PhaethonPsychis/playmaker/blob/main/MLVERC20.sol"; // a vending mchine for selling tickets contract vendor is Ownable{ //initiate token MLVERC20 public _MLVERC20; //contract state variables uint internal internal_number; uint256 public price; //uint public amountTickets; // Event that log buy operation event BuyTickets(address buyer, uint256 amountOfETH, uint256 amountOfTokens); event SellTokens(address seller, uint256 amountOfTokens, uint256 amountOfETH); constructor (address tokenAddress) { _MLVERC20 = MLVERC20(tokenAddress); } //owner sets a price for the ticket function setTicketPrice(uint _price) public onlyOwner { price = _price ; } function set_internal_number(uint _value) public { internal_number = _value; } function buyTickets(uint amountOfTickets) public payable returns (uint256){ //amountTickets = _amountTickets; require(msg.value >= amountOfTickets * price * 1 wei, "Not enough Eth to buy the tickets"); // check if the Vendor Contract has enough amount of tokens for the transaction uint256 vendorBalance = _MLVERC20.balanceOf(address(this)); require(vendorBalance >= amountOfTickets, "Vendor contract has not enough tokens in its balance"); // Transfer token to the msg.sender (bool sent) = _MLVERC20.transfer(msg.sender, amountOfTickets); require(sent, "Failed to transfer token to user"); // emit the event emit BuyTickets(msg.sender, msg.value, amountOfTickets); return amountOfTickets; } //Allow owner to withdraw ETH from contract function withdraw() public { payable(owner()).transfer(address(this).balance); } }
amountTickets = _amountTickets; check if the Vendor Contract has enough amount of tokens for the transaction Transfer token to the msg.sender emit the event
function buyTickets(uint amountOfTickets) public payable returns (uint256){ require(msg.value >= amountOfTickets * price * 1 wei, "Not enough Eth to buy the tickets"); uint256 vendorBalance = _MLVERC20.balanceOf(address(this)); require(vendorBalance >= amountOfTickets, "Vendor contract has not enough tokens in its balance"); (bool sent) = _MLVERC20.transfer(msg.sender, amountOfTickets); require(sent, "Failed to transfer token to user"); emit BuyTickets(msg.sender, msg.value, amountOfTickets); return amountOfTickets; }
13,043,491
[ 1, 8949, 6264, 2413, 273, 389, 8949, 6264, 2413, 31, 866, 309, 326, 776, 5227, 13456, 711, 7304, 3844, 434, 2430, 364, 326, 2492, 12279, 1147, 358, 326, 1234, 18, 15330, 3626, 326, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 6264, 2413, 12, 11890, 3844, 951, 6264, 2413, 13, 1071, 8843, 429, 1135, 261, 11890, 5034, 15329, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 3844, 951, 6264, 2413, 380, 6205, 380, 404, 732, 77, 16, 315, 1248, 7304, 512, 451, 358, 30143, 326, 24475, 8863, 203, 540, 203, 3639, 2254, 5034, 8556, 13937, 273, 389, 1495, 2204, 39, 3462, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2583, 12, 10645, 13937, 1545, 3844, 951, 6264, 2413, 16, 315, 14786, 6835, 711, 486, 7304, 2430, 316, 2097, 11013, 8863, 203, 540, 203, 3639, 261, 6430, 3271, 13, 273, 389, 1495, 2204, 39, 3462, 18, 13866, 12, 3576, 18, 15330, 16, 3844, 951, 6264, 2413, 1769, 203, 3639, 2583, 12, 7569, 16, 315, 2925, 358, 7412, 1147, 358, 729, 8863, 203, 203, 3639, 3626, 605, 9835, 6264, 2413, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 16, 3844, 951, 6264, 2413, 1769, 203, 203, 3639, 327, 3844, 951, 6264, 2413, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// 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 "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; 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; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; contract BBI is ERC20, Ownable { using SafeMath for uint256; modifier lockSwap() { _inSwap = true; _; _inSwap = false; } modifier liquidityAdd() { _inLiquidityAdd = true; _; _inLiquidityAdd = false; } // == CONSTANTS == uint256 public constant MAX_SUPPLY = 1_000_000_000 ether; uint256 public constant BPS_DENOMINATOR = 10_000; uint256 public constant SNIPE_BLOCKS = 2; // == LIMITS == /// @notice Wallet limit in wei. uint256 public walletLimit; /// @notice Buy limit in wei. uint256 public buyLimit; /// @notice Cooldown in seconds uint256 public cooldown = 20; // == TAXES == /// @notice Buy marketingTax in BPS uint256 public buyMarketingTax = 300; /// @notice Buy devTax in BPS uint256 public buyDevTax = 400; /// @notice Buy autoLiquidityTax in BPS uint256 public buyAutoLiquidityTax = 200; /// @notice Buy treasuryTax in BPS uint256 public buyTreasuryTax = 100; /// @notice Sell marketingTax in BPS uint256 public sellMarketingTax = 900; /// @notice Sell devTax in BPS uint256 public sellDevTax = 1000; /// @notice Sell autoLiquidityTax in BPS uint256 public sellAutoLiquidityTax = 400; /// @notice Sell treasuryTax in BPS uint256 public sellTreasuryTax = 200; /// @notice address that marketingTax is sent to address payable public marketingTaxWallet; /// @notice address that devTax is sent to address payable public devTaxWallet; /// @notice address that treasuryTax is sent to address payable public treasuryTaxWallet; /// @notice tokens that are allocated for marketingTax tax uint256 public totalMarketingTax; /// @notice tokens that are allocated for devTax tax uint256 public totalDevTax; /// @notice tokens that are allocated for auto liquidity tax uint256 public totalAutoLiquidityTax; /// @notice tokens that are allocated for treasury tax uint256 public totalTreasuryTax; // == FLAGS == /// @notice flag indicating Uniswap trading status bool public tradingActive = false; /// @notice flag indicating swapAll enabled bool public swapFees = true; // == UNISWAP == IUniswapV2Router02 public router = IUniswapV2Router02(address(0)); address public pair; // == WALLET STATUSES == /// @notice Maps each wallet to their tax exlcusion status mapping(address => bool) public taxExcluded; /// @notice Maps each wallet to the last timestamp they bought mapping(address => uint256) public lastBuy; /// @notice Maps each wallet to their blacklist status mapping(address => bool) public blacklist; /// @notice Maps each wallet to their whitelist status on buy limit mapping(address => bool) public walletLimitWhitelist; // == MISC == /// @notice Block when trading is first enabled uint256 public tradingBlock; // == INTERNAL == uint256 internal _totalSupply = 0; bool internal _inSwap = false; bool internal _inLiquidityAdd = false; mapping(address => uint256) private _balances; event MarketingTaxWalletChanged(address previousWallet, address nextWallet); event DevTaxWalletChanged(address previousWallet, address nextWallet); event TreasuryTaxWalletChanged(address previousWallet, address nextWallet); event BuyMarketingTaxChanged(uint256 previousTax, uint256 nextTax); event SellMarketingTaxChanged(uint256 previousTax, uint256 nextTax); event BuyDevTaxChanged(uint256 previousTax, uint256 nextTax); event SellDevTaxChanged(uint256 previousTax, uint256 nextTax); event BuyAutoLiquidityTaxChanged(uint256 previousTax, uint256 nextTax); event SellAutoLiquidityTaxChanged(uint256 previousTax, uint256 nextTax); event BuyTreasuryTaxChanged(uint256 previousTax, uint256 nextTax); event SellTreasuryTaxChanged(uint256 previousTax, uint256 nextTax); event MarketingTaxRescued(uint256 amount); event DevTaxRescued(uint256 amount); event AutoLiquidityTaxRescued(uint256 amount); event TreasuryTaxRescued(uint256 amount); event TradingActiveChanged(bool enabled); event TaxExclusionChanged(address user, bool taxExcluded); event MaxTransferChanged(uint256 previousMax, uint256 nextMax); event BuyLimitChanged(uint256 previousMax, uint256 nextMax); event WalletLimitChanged(uint256 previousMax, uint256 nextMax); event CooldownChanged(uint256 previousCooldown, uint256 nextCooldown); event BlacklistUpdated(address user, bool previousStatus, bool nextStatus); event SwapFeesChanged(bool previousStatus, bool nextStatus); event WalletLimitWhitelistUpdated( address user, bool previousStatus, bool nextStatus ); constructor( address _factory, address _router, uint256 _buyLimit, uint256 _walletLimit, address payable _marketingTaxWallet, address payable _devTaxWallet, address payable _treasuryTaxWallet ) ERC20("Butkus Balboa Inu", "BBI") Ownable() { taxExcluded[owner()] = true; taxExcluded[address(0)] = true; taxExcluded[_marketingTaxWallet] = true; taxExcluded[_devTaxWallet] = true; taxExcluded[address(this)] = true; buyLimit = _buyLimit; walletLimit = _walletLimit; marketingTaxWallet = _marketingTaxWallet; devTaxWallet = _devTaxWallet; treasuryTaxWallet = _treasuryTaxWallet; router = IUniswapV2Router02(_router); IUniswapV2Factory uniswapContract = IUniswapV2Factory(_factory); pair = uniswapContract.createPair(address(this), router.WETH()); _updateWalletLimitWhitelist(address(this), true); _updateWalletLimitWhitelist(pair, true); } /// @notice Change the address of the buyback wallet /// @param _marketingTaxWallet The new address of the buyback wallet function setMarketingTaxWallet(address payable _marketingTaxWallet) external onlyOwner { emit MarketingTaxWalletChanged(marketingTaxWallet, _marketingTaxWallet); marketingTaxWallet = _marketingTaxWallet; } /// @notice Change the address of the devTax wallet /// @param _devTaxWallet The new address of the devTax wallet function setDevTaxWallet(address payable _devTaxWallet) external onlyOwner { emit DevTaxWalletChanged(devTaxWallet, _devTaxWallet); devTaxWallet = _devTaxWallet; } /// @notice Change the address of the treasuryTax wallet /// @param _treasuryTaxWallet The new address of the treasuryTax wallet function setTreasuryTaxWallet(address payable _treasuryTaxWallet) external onlyOwner { emit TreasuryTaxWalletChanged(treasuryTaxWallet, _treasuryTaxWallet); treasuryTaxWallet = _treasuryTaxWallet; } /// @notice Change the buy marketingTax rate /// @param _buyMarketingTax The new buy marketingTax rate function setBuyMarketingTax(uint256 _buyMarketingTax) external onlyOwner { require( _buyMarketingTax <= BPS_DENOMINATOR, "_buyMarketingTax cannot exceed BPS_DENOMINATOR" ); emit BuyMarketingTaxChanged(buyMarketingTax, _buyMarketingTax); buyMarketingTax = _buyMarketingTax; } /// @notice Change the sell marketingTax rate /// @param _sellMarketingTax The new sell marketingTax rate function setSellMarketingTax(uint256 _sellMarketingTax) external onlyOwner { require( _sellMarketingTax <= BPS_DENOMINATOR, "_sellMarketingTax cannot exceed BPS_DENOMINATOR" ); emit SellMarketingTaxChanged(sellMarketingTax, _sellMarketingTax); sellMarketingTax = _sellMarketingTax; } /// @notice Change the buy devTax rate /// @param _buyDevTax The new devTax rate function setBuyDevTax(uint256 _buyDevTax) external onlyOwner { require( _buyDevTax <= BPS_DENOMINATOR, "_buyDevTax cannot exceed BPS_DENOMINATOR" ); emit BuyDevTaxChanged(buyDevTax, _buyDevTax); buyDevTax = _buyDevTax; } /// @notice Change the buy devTax rate /// @param _sellDevTax The new devTax rate function setSellDevTax(uint256 _sellDevTax) external onlyOwner { require( _sellDevTax <= BPS_DENOMINATOR, "_sellDevTax cannot exceed BPS_DENOMINATOR" ); emit SellDevTaxChanged(sellDevTax, _sellDevTax); sellDevTax = _sellDevTax; } /// @notice Change the buy autoLiquidityTax rate /// @param _buyAutoLiquidityTax The new buy autoLiquidityTax rate function setBuyAutoLiquidityTax(uint256 _buyAutoLiquidityTax) external onlyOwner { require( _buyAutoLiquidityTax <= BPS_DENOMINATOR, "_buyAutoLiquidityTax cannot exceed BPS_DENOMINATOR" ); emit BuyAutoLiquidityTaxChanged( buyAutoLiquidityTax, _buyAutoLiquidityTax ); buyAutoLiquidityTax = _buyAutoLiquidityTax; } /// @notice Change the sell autoLiquidityTax rate /// @param _sellAutoLiquidityTax The new sell autoLiquidityTax rate function setSellAutoLiquidityTax(uint256 _sellAutoLiquidityTax) external onlyOwner { require( _sellAutoLiquidityTax <= BPS_DENOMINATOR, "_sellAutoLiquidityTax cannot exceed BPS_DENOMINATOR" ); emit SellAutoLiquidityTaxChanged( sellAutoLiquidityTax, _sellAutoLiquidityTax ); sellAutoLiquidityTax = _sellAutoLiquidityTax; } /// @notice Change the buy treasuryTax rate /// @param _buyTreasuryTax The new treasuryTax rate function setBuyTreasuryTax(uint256 _buyTreasuryTax) external onlyOwner { require( _buyTreasuryTax <= BPS_DENOMINATOR, "_buyTreasuryTax cannot exceed BPS_DENOMINATOR" ); emit BuyTreasuryTaxChanged(buyTreasuryTax, _buyTreasuryTax); buyTreasuryTax = _buyTreasuryTax; } /// @notice Change the buy treasuryTax rate /// @param _sellTreasuryTax The new treasuryTax rate function setSellTreasuryTax(uint256 _sellTreasuryTax) external onlyOwner { require( _sellTreasuryTax <= BPS_DENOMINATOR, "_sellTreasuryTax cannot exceed BPS_DENOMINATOR" ); emit SellTreasuryTaxChanged(sellTreasuryTax, _sellTreasuryTax); sellTreasuryTax = _sellTreasuryTax; } /// @notice Change the cooldown for buys /// @param _cooldown The new cooldown in seconds function setCooldown(uint256 _cooldown) external onlyOwner { emit CooldownChanged(cooldown, _cooldown); cooldown = _cooldown; } /// @notice Rescue BBI from the marketingTax amount /// @dev Should only be used in an emergency /// @param _amount The amount of BBI to rescue /// @param _recipient The recipient of the rescued BBI function rescueMarketingTaxTokens(uint256 _amount, address _recipient) external onlyOwner { require( _amount <= totalMarketingTax, "Amount cannot be greater than totalMarketingTax" ); _rawTransfer(address(this), _recipient, _amount); emit MarketingTaxRescued(_amount); totalMarketingTax -= _amount; } /// @notice Rescue BBI from the devTax amount /// @dev Should only be used in an emergency /// @param _amount The amount of BBI to rescue /// @param _recipient The recipient of the rescued BBI function rescueDevTaxTokens(uint256 _amount, address _recipient) external onlyOwner { require( _amount <= totalDevTax, "Amount cannot be greater than totalDevTax" ); _rawTransfer(address(this), _recipient, _amount); emit DevTaxRescued(_amount); totalDevTax -= _amount; } /// @notice Rescue BBI from the autoLiquidityTax amount /// @dev Should only be used in an emergency /// @param _amount The amount of BBI to rescue /// @param _recipient The recipient of the rescued BBI function rescueAutoLiquidityTaxTokens(uint256 _amount, address _recipient) external onlyOwner { require( _amount <= totalAutoLiquidityTax, "Amount cannot be greater than totalAutoLiquidityTax" ); _rawTransfer(address(this), _recipient, _amount); emit AutoLiquidityTaxRescued(_amount); totalAutoLiquidityTax -= _amount; } /// @notice Rescue BBI from the treasuryTax amount /// @dev Should only be used in an emergency /// @param _amount The amount of BBI to rescue /// @param _recipient The recipient of the rescued BBI function rescueTreasuryTaxTokens(uint256 _amount, address _recipient) external onlyOwner { require( _amount <= totalTreasuryTax, "Amount cannot be greater than totalTreasuryTax" ); _rawTransfer(address(this), _recipient, _amount); emit TreasuryTaxRescued(_amount); totalTreasuryTax -= _amount; } function addLiquidity(uint256 tokens) external payable onlyOwner liquidityAdd { _mint(address(this), tokens); _approve(address(this), address(router), tokens); router.addLiquidityETH{value: msg.value}( address(this), tokens, 0, 0, owner(), // solhint-disable-next-line not-rely-on-time block.timestamp ); } /// @notice Admin function to update a wallet's blacklist status /// @param user the wallet /// @param status the new status function updateBlacklist(address user, bool status) external virtual onlyOwner { _updateBlacklist(user, status); } function _updateBlacklist(address user, bool status) internal virtual { emit BlacklistUpdated(user, blacklist[user], status); blacklist[user] = status; } /// @notice Admin function to update a wallet's buy limit status /// @param user the wallet /// @param status the new status function updateWalletLimitWhitelist(address user, bool status) external virtual onlyOwner { _updateWalletLimitWhitelist(user, status); } function _updateWalletLimitWhitelist(address user, bool status) internal virtual { emit WalletLimitWhitelistUpdated( user, walletLimitWhitelist[user], status ); walletLimitWhitelist[user] = status; } /// @notice Enables or disables trading on Uniswap function setTradingActive(bool _tradingActive) external onlyOwner { if (_tradingActive && tradingBlock == 0) { tradingBlock = block.number; } tradingActive = _tradingActive; emit TradingActiveChanged(_tradingActive); } /// @notice Updates tax exclusion status /// @param _account Account to update the tax exclusion status of /// @param _taxExcluded If true, exclude taxes for this user function setTaxExcluded(address _account, bool _taxExcluded) public onlyOwner { taxExcluded[_account] = _taxExcluded; emit TaxExclusionChanged(_account, _taxExcluded); } /// @notice Updates the max amount allowed to buy /// @param _buyLimit The new buy limit function setBuyLimit(uint256 _buyLimit) external onlyOwner { emit BuyLimitChanged(buyLimit, _buyLimit); buyLimit = _buyLimit; } /// @notice Updates the max amount allowed to be held by a single wallet /// @param _walletLimit The new max function setWalletLimit(uint256 _walletLimit) external onlyOwner { emit WalletLimitChanged(walletLimit, _walletLimit); walletLimit = _walletLimit; } /// @notice Enable or disable whether swap occurs during `_transfer` /// @param _swapFees If true, enables swap during `_transfer` function setSwapFees(bool _swapFees) external onlyOwner { emit SwapFeesChanged(swapFees, _swapFees); swapFees = _swapFees; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function _addBalance(address account, uint256 amount) internal { _balances[account] = _balances[account] + amount; } function _subtractBalance(address account, uint256 amount) internal { _balances[account] = _balances[account] - amount; } function _transfer( address sender, address recipient, uint256 amount ) internal override { require(!blacklist[recipient], "Recipient is blacklisted"); if (taxExcluded[sender] || taxExcluded[recipient]) { _rawTransfer(sender, recipient, amount); return; } // Enforce wallet limits if (!walletLimitWhitelist[recipient]) { require( balanceOf(recipient).add(amount) <= walletLimit, "Wallet limit exceeded" ); } uint256 send = amount; uint256 marketingTax; uint256 devTax; uint256 autoLiquidityTax; uint256 treasuryTax; if (sender == pair) { require(tradingActive, "Trading is not yet active"); require( balanceOf(recipient).add(amount) <= buyLimit, "Buy limit exceeded" ); if (block.number <= tradingBlock + SNIPE_BLOCKS) { _updateBlacklist(recipient, true); } if (cooldown > 0) { require( lastBuy[recipient] + cooldown <= block.timestamp, "Cooldown still active" ); lastBuy[recipient] = block.timestamp; } ( send, marketingTax, devTax, autoLiquidityTax, treasuryTax ) = _getTaxAmounts(amount, true); } else if (recipient == pair) { require(tradingActive, "Trading is not yet active"); if (swapFees) swapAll(); ( send, marketingTax, devTax, autoLiquidityTax, treasuryTax ) = _getTaxAmounts(amount, false); } _rawTransfer(sender, recipient, send); _takeTaxes(sender, marketingTax, devTax, autoLiquidityTax, treasuryTax); } /// @notice Peforms auto liquidity and tax distribution function swapAll() public lockSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = router.WETH(); // Auto-liquidity uint256 autoLiquidityAmount = totalAutoLiquidityTax.div(2); uint256 walletTaxes = totalMarketingTax.add(totalDevTax).add( totalTreasuryTax ); _approve( address(this), address(router), walletTaxes.add(totalAutoLiquidityTax) ); router.swapExactTokensForETHSupportingFeeOnTransferTokens( autoLiquidityAmount.add(walletTaxes), 0, // accept any amount of ETH path, address(this), block.timestamp ); router.addLiquidityETH{value: address(this).balance}( address(this), autoLiquidityAmount, 0, 0, address(0xdead), block.timestamp ); totalAutoLiquidityTax = 0; // Distribute remaining taxes uint256 contractEth = address(this).balance; uint256 marketingTaxEth = contractEth.mul(totalMarketingTax).div( walletTaxes ); uint256 devTaxEth = contractEth.mul(totalDevTax).div(walletTaxes); uint256 treasuryTaxEth = contractEth.mul(totalTreasuryTax).div( walletTaxes ); totalMarketingTax = 0; totalDevTax = 0; totalTreasuryTax = 0; if (marketingTaxEth > 0) { marketingTaxWallet.transfer(marketingTaxEth); } if (devTaxEth > 0) { devTaxWallet.transfer(devTaxEth); } if (treasuryTaxEth > 0) { treasuryTaxWallet.transfer(treasuryTaxEth); } } /// @notice Admin function to rescue ETH from the contract function rescueETH() external onlyOwner { payable(owner()).transfer(address(this).balance); } /// @notice Transfers BBI from an account to this contract for taxes /// @param _account The account to transfer BBI from /// @param _marketingTaxAmount The amount of marketingTax tax to transfer /// @param _devTaxAmount The amount of devTax tax to transfer function _takeTaxes( address _account, uint256 _marketingTaxAmount, uint256 _devTaxAmount, uint256 _autoLiquidityTaxAmount, uint256 _treasuryTaxAmount ) internal { require(_account != address(0), "taxation from the zero address"); uint256 totalAmount = _marketingTaxAmount .add(_devTaxAmount) .add(_autoLiquidityTaxAmount) .add(_treasuryTaxAmount); _rawTransfer(_account, address(this), totalAmount); totalMarketingTax += _marketingTaxAmount; totalDevTax += _devTaxAmount; totalAutoLiquidityTax += _autoLiquidityTaxAmount; totalTreasuryTax += _treasuryTaxAmount; } /// @notice Get a breakdown of send and tax amounts /// @param amount The amount to tax in wei /// @return send The raw amount to send /// @return marketingTax The raw marketingTax tax amount /// @return devTax The raw devTax tax amount function _getTaxAmounts(uint256 amount, bool buying) internal view returns ( uint256 send, uint256 marketingTax, uint256 devTax, uint256 autoLiquidityTax, uint256 treasuryTax ) { if (buying) { marketingTax = amount.mul(buyMarketingTax).div(BPS_DENOMINATOR); devTax = amount.mul(buyDevTax).div(BPS_DENOMINATOR); autoLiquidityTax = amount.mul(buyAutoLiquidityTax).div( BPS_DENOMINATOR ); treasuryTax = amount.mul(buyTreasuryTax).div(BPS_DENOMINATOR); } else { marketingTax = amount.mul(sellMarketingTax).div(BPS_DENOMINATOR); devTax = amount.mul(sellDevTax).div(BPS_DENOMINATOR); autoLiquidityTax = amount.mul(sellAutoLiquidityTax).div( BPS_DENOMINATOR ); treasuryTax = amount.mul(sellTreasuryTax).div(BPS_DENOMINATOR); } send = amount.sub(marketingTax).sub(devTax).sub(autoLiquidityTax).sub( treasuryTax ); } // modified from OpenZeppelin ERC20 function _rawTransfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "transfer from the zero address"); require(recipient != address(0), "transfer to the zero address"); uint256 senderBalance = balanceOf(sender); require(senderBalance >= amount, "transfer amount exceeds balance"); unchecked { _subtractBalance(sender, amount); } _addBalance(recipient, amount); emit Transfer(sender, recipient, amount); } function totalSupply() public view override returns (uint256) { return _totalSupply; } function _mint(address account, uint256 amount) internal override { require(_totalSupply.add(amount) <= MAX_SUPPLY, "Max supply exceeded"); _totalSupply += amount; _addBalance(account, amount); emit Transfer(address(0), account, amount); } function mint(address account, uint256 amount) external onlyOwner { _mint(account, amount); } function airdrop(address[] memory accounts, uint256[] memory amounts) external onlyOwner { require(accounts.length == amounts.length, "array lengths must match"); for (uint256 i = 0; i < accounts.length; i++) { _mint(accounts[i], amounts[i]); } } receive() external payable {} } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } }
== MISC == @notice Block when trading is first enabled
uint256 public tradingBlock;
1,608,840
[ 1, 631, 20806, 2312, 422, 225, 3914, 1347, 1284, 7459, 353, 1122, 3696, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 1284, 7459, 1768, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x9C9e5E393f2445d7E7FF885839ABCbCE125Fd012/sources/contracts/L1/fraud-proof/libraries/MerkleLib.sol
Get the original and updated Element Merkle Root, given append leaf and an Append Proof
function get_roots_from_leaf_and_append_proof_single_append(bytes32 append_leaf, bytes32[] memory proof) internal pure returns (bytes32 hash, bytes32 scratch) { uint256 proof_index = bit_count_32(uint32(uint256(proof[0]))); hash = proof[proof_index]; append_leaf = hash_node(hash, append_leaf); while (proof_index > 1) { proof_index -= 1; scratch = proof[proof_index]; append_leaf = hash_node(scratch, append_leaf); hash = hash_node(scratch, hash); } return (hash, append_leaf); }
1,906,010
[ 1, 967, 326, 2282, 471, 3526, 3010, 31827, 7450, 16, 864, 714, 7839, 471, 392, 6181, 1186, 792, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 67, 22078, 67, 2080, 67, 12070, 67, 464, 67, 6923, 67, 24207, 67, 7526, 67, 6923, 12, 3890, 1578, 714, 67, 12070, 16, 1731, 1578, 8526, 3778, 14601, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 3890, 1578, 1651, 16, 1731, 1578, 15289, 13, 203, 565, 288, 203, 3639, 2254, 5034, 14601, 67, 1615, 273, 2831, 67, 1883, 67, 1578, 12, 11890, 1578, 12, 11890, 5034, 12, 24207, 63, 20, 22643, 1769, 203, 3639, 1651, 273, 14601, 63, 24207, 67, 1615, 15533, 203, 3639, 714, 67, 12070, 273, 1651, 67, 2159, 12, 2816, 16, 714, 67, 12070, 1769, 203, 203, 3639, 1323, 261, 24207, 67, 1615, 405, 404, 13, 288, 203, 5411, 14601, 67, 1615, 3947, 404, 31, 203, 5411, 15289, 273, 14601, 63, 24207, 67, 1615, 15533, 203, 5411, 714, 67, 12070, 273, 1651, 67, 2159, 12, 24638, 505, 16, 714, 67, 12070, 1769, 203, 5411, 1651, 273, 1651, 67, 2159, 12, 24638, 505, 16, 1651, 1769, 203, 3639, 289, 203, 203, 3639, 327, 261, 2816, 16, 714, 67, 12070, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x0b57718Cb5e8C376613527161b086e57550FB84a/sources/mefi/MefiClient.sol
* @title The MefiClient contract @notice Contract writers can inherit this contract in order to create requests for the Mefi network/
contract MefiClient { using Mefi for Mefi.Request; uint256 constant internal MDT = 10 ** 18; uint256 constant private AMOUNT_OVERRIDE = 0; address constant private SENDER_OVERRIDE = address(0); uint256 constant private ARGS_VERSION = 1; bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("mdt"); bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle"); uint256 constant private CHAIN_ID_MAINNET = 1; uint256 constant private CHAIN_ID_RINKEBY = 4; ENSInterface private ens; bytes32 private ensNode; MDTTokenInterface private mdt; MefiRequestInterface private oracle; uint256 private requestCount = 1; mapping(bytes32 => address) private pendingRequests; address internal oracleAddress; event MefiRequested(bytes32 indexed id); event MefiFulfilled(bytes32 indexed id); event MefiCancelled(bytes32 indexed id); pragma solidity ^0.6.0; import {ENSResolver as ENSResolver_Mefi} from "./vendor/ENSResolver.sol"; function setOracleAddress(address _oracleAddress) public { oracleAddress = _oracleAddress; setMefiOracle(oracleAddress); } function getOracleAddress() public view returns (address) { return oracleAddress; } function buildMefiRequest( bytes32 _specId, address _callbackAddress, bytes4 _callbackFunctionSignature ) internal pure returns (Mefi.Request memory) { Mefi.Request memory req; return req.initialize(_specId, _callbackAddress, _callbackFunctionSignature); } function buildMefiStockPriceRequest( bytes32 _specId, string memory _symbol, address _callbackAddress, bytes4 _callbackFunctionSignature ) internal pure returns (Mefi.Request memory) { Mefi.Request memory req; req = req.initialize(_specId, _callbackAddress, _callbackFunctionSignature); req.add("symbol", _symbol); return req; } function sendMefiRequest(Mefi.Request memory _req, uint256 _payment) internal returns (bytes32) { return sendMefiRequestTo(address(oracle), _req, _payment); } function sendMefiRequestTo(address _oracle, Mefi.Request memory _req, uint256 _payment) internal returns (bytes32 requestId) { requestId = keccak256(abi.encodePacked(this, requestCount)); _req.nonce = requestCount; pendingRequests[requestId] = _oracle; emit MefiRequested(requestId); require(mdt.transferAndCall(_oracle, _payment, encodeRequest(_req)), "unable to transferAndCall to oracle"); requestCount += 1; return requestId; } function cancelMefiRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunc, uint256 _expiration ) internal { MefiRequestInterface requested = MefiRequestInterface(pendingRequests[_requestId]); delete pendingRequests[_requestId]; emit MefiCancelled(_requestId); requested.cancelOracleRequest(_requestId, _payment, _callbackFunc, _expiration); } function setMefiOracle(address _oracle) internal { oracle = MefiRequestInterface(_oracle); } function setMefiToken(address _mdt) internal { mdt = MDTTokenInterface(_mdt); } function getChainID() internal pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } function getChainID() internal pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } function setPublicMefiToken() internal { uint256 chainId = getChainID(); require(CHAIN_ID_MAINNET == chainId || CHAIN_ID_RINKEBY == chainId, 'Client is deployed on chain without MDT contract'); if (CHAIN_ID_MAINNET == chainId) { setMefiToken(MDT_TOKEN_ADDRESS_MAINNET); setMefiToken(MDT_TOKEN_ADDRESS_RINKEBY); } } function setPublicMefiToken() internal { uint256 chainId = getChainID(); require(CHAIN_ID_MAINNET == chainId || CHAIN_ID_RINKEBY == chainId, 'Client is deployed on chain without MDT contract'); if (CHAIN_ID_MAINNET == chainId) { setMefiToken(MDT_TOKEN_ADDRESS_MAINNET); setMefiToken(MDT_TOKEN_ADDRESS_RINKEBY); } } } else if (CHAIN_ID_RINKEBY == chainId) { function mefiTokenAddress() internal view returns (address) { return address(mdt); } function mefiOracleAddress() internal view returns (address) { return address(oracle); } function addMefiExternalRequest(address _oracle, bytes32 _requestId) internal notPendingRequest(_requestId) { pendingRequests[_requestId] = _oracle; } function useMefiWithENS(address _ens, bytes32 _node) internal { ens = ENSInterface(_ens); ensNode = _node; bytes32 mdtSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME)); ENSResolver_Mefi resolver = ENSResolver_Mefi(ens.resolver(mdtSubnode)); setMefiToken(resolver.addr(mdtSubnode)); updateMefiOracleWithENS(); } function updateMefiOracleWithENS() internal { bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME)); ENSResolver_Mefi resolver = ENSResolver_Mefi(ens.resolver(oracleSubnode)); setMefiOracle(resolver.addr(oracleSubnode)); } function encodeRequest(Mefi.Request memory _req) private view returns (bytes memory) { return abi.encodeWithSelector( oracle.oracleRequest.selector, _req.id, _req.callbackAddress, _req.callbackFunctionId, _req.nonce, ARGS_VERSION, _req.buf.buf); } {} function validateMefiCallback(bytes32 _requestId) internal recordMefiFulfillment(_requestId) function readStockPriceWithTime(bytes32 x) internal pure returns (uint[] memory) { bytes memory bytesString = new bytes(32); uint len = 0; for (uint i = 0; i < 32; i++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * i))); if (char != 0) { bytesString[len++] = char; } } uint count = 2; uint[] memory data = new uint[](count); for (uint i = 0; i < count; i++) { data[i] = 0; } uint index = 0; for (uint i = 0; i < len || count < 2; i++) { uint c = uint(uint8(bytesString[i])); if (c >= 48 && c <= 57) { data[index] = data[index] * 10 + c - 48; if (data[index] > 0) { index++; } } } return data; } function validateMefiCallback(bytes32 _requestId) internal recordMefiFulfillment(_requestId) function readStockPriceWithTime(bytes32 x) internal pure returns (uint[] memory) { bytes memory bytesString = new bytes(32); uint len = 0; for (uint i = 0; i < 32; i++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * i))); if (char != 0) { bytesString[len++] = char; } } uint count = 2; uint[] memory data = new uint[](count); for (uint i = 0; i < count; i++) { data[i] = 0; } uint index = 0; for (uint i = 0; i < len || count < 2; i++) { uint c = uint(uint8(bytesString[i])); if (c >= 48 && c <= 57) { data[index] = data[index] * 10 + c - 48; if (data[index] > 0) { index++; } } } return data; } function validateMefiCallback(bytes32 _requestId) internal recordMefiFulfillment(_requestId) function readStockPriceWithTime(bytes32 x) internal pure returns (uint[] memory) { bytes memory bytesString = new bytes(32); uint len = 0; for (uint i = 0; i < 32; i++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * i))); if (char != 0) { bytesString[len++] = char; } } uint count = 2; uint[] memory data = new uint[](count); for (uint i = 0; i < count; i++) { data[i] = 0; } uint index = 0; for (uint i = 0; i < len || count < 2; i++) { uint c = uint(uint8(bytesString[i])); if (c >= 48 && c <= 57) { data[index] = data[index] * 10 + c - 48; if (data[index] > 0) { index++; } } } return data; } function validateMefiCallback(bytes32 _requestId) internal recordMefiFulfillment(_requestId) function readStockPriceWithTime(bytes32 x) internal pure returns (uint[] memory) { bytes memory bytesString = new bytes(32); uint len = 0; for (uint i = 0; i < 32; i++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * i))); if (char != 0) { bytesString[len++] = char; } } uint count = 2; uint[] memory data = new uint[](count); for (uint i = 0; i < count; i++) { data[i] = 0; } uint index = 0; for (uint i = 0; i < len || count < 2; i++) { uint c = uint(uint8(bytesString[i])); if (c >= 48 && c <= 57) { data[index] = data[index] * 10 + c - 48; if (data[index] > 0) { index++; } } } return data; } function validateMefiCallback(bytes32 _requestId) internal recordMefiFulfillment(_requestId) function readStockPriceWithTime(bytes32 x) internal pure returns (uint[] memory) { bytes memory bytesString = new bytes(32); uint len = 0; for (uint i = 0; i < 32; i++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * i))); if (char != 0) { bytesString[len++] = char; } } uint count = 2; uint[] memory data = new uint[](count); for (uint i = 0; i < count; i++) { data[i] = 0; } uint index = 0; for (uint i = 0; i < len || count < 2; i++) { uint c = uint(uint8(bytesString[i])); if (c >= 48 && c <= 57) { data[index] = data[index] * 10 + c - 48; if (data[index] > 0) { index++; } } } return data; } function validateMefiCallback(bytes32 _requestId) internal recordMefiFulfillment(_requestId) function readStockPriceWithTime(bytes32 x) internal pure returns (uint[] memory) { bytes memory bytesString = new bytes(32); uint len = 0; for (uint i = 0; i < 32; i++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * i))); if (char != 0) { bytesString[len++] = char; } } uint count = 2; uint[] memory data = new uint[](count); for (uint i = 0; i < count; i++) { data[i] = 0; } uint index = 0; for (uint i = 0; i < len || count < 2; i++) { uint c = uint(uint8(bytesString[i])); if (c >= 48 && c <= 57) { data[index] = data[index] * 10 + c - 48; if (data[index] > 0) { index++; } } } return data; } } else { function validateMefiCallback(bytes32 _requestId) internal recordMefiFulfillment(_requestId) function readStockPriceWithTime(bytes32 x) internal pure returns (uint[] memory) { bytes memory bytesString = new bytes(32); uint len = 0; for (uint i = 0; i < 32; i++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * i))); if (char != 0) { bytesString[len++] = char; } } uint count = 2; uint[] memory data = new uint[](count); for (uint i = 0; i < count; i++) { data[i] = 0; } uint index = 0; for (uint i = 0; i < len || count < 2; i++) { uint c = uint(uint8(bytesString[i])); if (c >= 48 && c <= 57) { data[index] = data[index] * 10 + c - 48; if (data[index] > 0) { index++; } } } return data; } function stringToBytes32(string memory source) internal pure returns (bytes32 result) { bytes memory b = bytes(source); if (b.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function stringToBytes32(string memory source) internal pure returns (bytes32 result) { bytes memory b = bytes(source); if (b.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function stringToBytes32(string memory source) internal pure returns (bytes32 result) { bytes memory b = bytes(source); if (b.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function bytes32ToString(bytes32 x) internal pure returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } function bytes32ToString(bytes32 x) internal pure returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } function bytes32ToString(bytes32 x) internal pure returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } function bytes32ToString(bytes32 x) internal pure returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } modifier recordMefiFulfillment(bytes32 _requestId) { require(msg.sender == pendingRequests[_requestId], "Source must be the oracle of the request"); delete pendingRequests[_requestId]; emit MefiFulfilled(_requestId); _; } modifier notPendingRequest(bytes32 _requestId) { require(pendingRequests[_requestId] == address(0), "Request is already pending"); _; } }
12,479,495
[ 1, 1986, 7499, 22056, 1227, 6835, 225, 13456, 18656, 848, 6811, 333, 6835, 316, 1353, 358, 752, 3285, 364, 326, 7499, 22056, 2483, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7499, 22056, 1227, 288, 203, 565, 1450, 7499, 22056, 364, 7499, 22056, 18, 691, 31, 203, 203, 565, 2254, 5034, 5381, 2713, 490, 9081, 273, 1728, 2826, 6549, 31, 203, 565, 2254, 5034, 5381, 3238, 432, 5980, 5321, 67, 31514, 273, 374, 31, 203, 565, 1758, 5381, 3238, 348, 22457, 67, 31514, 273, 1758, 12, 20, 1769, 203, 565, 2254, 5034, 5381, 3238, 13984, 55, 67, 5757, 273, 404, 31, 203, 565, 1731, 1578, 5381, 3238, 512, 3156, 67, 8412, 67, 8362, 1985, 273, 417, 24410, 581, 5034, 2932, 1264, 88, 8863, 203, 565, 1731, 1578, 5381, 3238, 512, 3156, 67, 916, 2226, 900, 67, 8362, 1985, 273, 417, 24410, 581, 5034, 2932, 280, 16066, 8863, 203, 203, 565, 2254, 5034, 5381, 3238, 6469, 6964, 67, 734, 67, 19803, 14843, 273, 404, 31, 203, 565, 2254, 5034, 5381, 3238, 6469, 6964, 67, 734, 67, 54, 706, 6859, 6486, 273, 1059, 31, 203, 203, 565, 512, 3156, 1358, 3238, 19670, 31, 203, 565, 1731, 1578, 3238, 19670, 907, 31, 203, 565, 490, 9081, 1345, 1358, 3238, 3481, 88, 31, 203, 565, 7499, 22056, 13398, 3238, 20865, 31, 203, 565, 2254, 5034, 3238, 590, 1380, 273, 404, 31, 203, 565, 2874, 12, 3890, 1578, 516, 1758, 13, 3238, 4634, 6421, 31, 203, 203, 565, 1758, 2713, 20865, 1887, 31, 203, 203, 565, 871, 7499, 22056, 11244, 12, 3890, 1578, 8808, 612, 1769, 203, 565, 871, 7499, 22056, 23747, 13968, 12, 3890, 1578, 8808, 612, 1769, 203, 565, 871, 7499, 22056, 21890, 12, 3890, 1578, 8808, 2 ]
./full_match/80001/0xD068603a8D7A36df7530e708B3A62D3BFD333E96/sources/contracts/module/SLG-Miralce-Stake.sol
@dev Mapping of player addresses to their NFT By default, player has no NFT. They will not be in the mapping.
mapping(address => StakeMap) public StakePlayer;
9,445,286
[ 1, 3233, 434, 7291, 6138, 358, 3675, 423, 4464, 2525, 805, 16, 7291, 711, 1158, 423, 4464, 18, 16448, 903, 486, 506, 316, 326, 2874, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 934, 911, 863, 13, 1071, 934, 911, 12148, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "./interfaces/ITokensPolicyRegistry.sol"; import "../../request-verification-layer/permission-module/Protected.sol"; import "../../registry-layer/components-registry/instances/TokensFactoryInstance.sol"; /** * @title TokensPolicyRegistry */ contract TokensPolicyRegistry is ITokensPolicyRegistry, Protected, TokensFactoryInstance { // Declare storage for tokens policies // token => action => policy mapping(address => mapping(bytes32 => bytes)) policies; // Declare storage for policy hash // token => action => policy hash mapping(address => mapping(bytes32 => bytes32)) policyHash; // Declare storage for policies with ids // token => action => id => policy mapping(address => mapping(bytes32 => mapping(bytes32 => bytes))) policiesWithIds; // Declare storage for policy hash // token => action => id => policy hash mapping(address => mapping(bytes32 => mapping(bytes32 => bytes32))) policyWithIdHash; // Write info to the log when a policy was set event Policy(address indexed token, bytes32 action, bytes policy); /** * @notice Verify token address */ modifier onlyRegisteredToken(address tokenAddress) { require( tfInstance().getTokenStandard(tokenAddress) != 0x00, "Token is not registered in the tokens factory." ); _; } // Initialize contract constructor(address componentsRegistry) public WithComponentsRegistry(componentsRegistry) {} /** * @notice Set policy for the token action * @param token Token address * @param action Action * @param policy Token policy for the specified action */ function setPolicy(address token, bytes32 action, bytes calldata policy) external verifyPermissionForToken(msg.sig, msg.sender, token) onlyRegisteredToken(token) { require(token != address(0), "Invalid token address."); require(action != bytes32(0x00), "Invalid action."); policies[token][action] = policy; policyHash[token][action] = keccak256(policy); emit Policy(token, action, policy); } /** * @notice Set policy for the token action * @param token Token address * @param action Action * @param id Additional identifier * @param policy Token policy for the specified action */ function setPolicyWithId( address token, bytes32 action, bytes32 id, bytes calldata policy ) external allowedForTokenWithSubId(msg.sig, msg.sender, token, id) onlyRegisteredToken(token) { require(token != address(0), "Invalid token address"); require(action != bytes32(0x00), "Invalid action"); require(id != bytes32(0x00), "Invalid identifier"); policiesWithIds[token][action][id] = policy; policyWithIdHash[token][action][id] = keccak256(policy); emit Policy(token, action, policy); } /** * @notice Returns policy for specified action and token * @param token Token address * @param action Action */ function getPolicy(address token, bytes32 action) public view returns (bytes memory) { return policies[token][action]; } /** * @notice Returns policy for specified action and token * @param token Token address * @param action Action * @param id Additional id */ function getPolicyById(address token, bytes32 action, bytes32 id) public view returns (bytes memory) { return policiesWithIds[token][action][id]; } /** * @notice Returns policy hash for specified action and token * @param token Token address * @param action Action */ function getPolicyHash(address token, bytes32 action) public view returns (bytes32) { return policyHash[token][action]; } /** * @notice Returns policy hash for specified action and token * @param token Token address * @param action Action * @param id Additional id */ function getPolicyHashById(address token, bytes32 action, bytes32 id) public view returns (bytes32) { return policyWithIdHash[token][action][id]; } /** * @notice Returns policy length * @param token Token address * @param action Action */ function getPolicyLength(address token, bytes32 action) public view returns (uint) { return policies[token][action].length; } /** * @notice Returns policy length * @param token Token address * @param action Action * @param id Additional id */ function getPolicyWithIdLength(address token, bytes32 action, bytes32 id) public view returns (uint) { return policiesWithIds[token][action][id].length; } }
* @notice Returns policy for specified action and token @param token Token address @param action Action/
function getPolicy(address token, bytes32 action) public view returns (bytes memory) { return policies[token][action]; }
7,215,995
[ 1, 1356, 3329, 364, 1269, 1301, 471, 1147, 225, 1147, 3155, 1758, 225, 1301, 4382, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1689, 1590, 12, 2867, 1147, 16, 1731, 1578, 1301, 13, 1071, 1476, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 8923, 63, 2316, 6362, 1128, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; import "zeppelin/contracts/lifecycle/Pausable.sol"; /** * @title EtherSign - document signing affordably on the Ethereum blockchain! * @notice This contract opt for storing document through firing of events as a (much) cheaper alternative than storing the document in storage since string storage on Ethereum blockchain is extremely expensive. For more detailed design pattern explaination, please refer to design_pattern_desicions.md * @dev the contract can be paused by owner in case of catastrophic bugs. Contract can be then upgraded and frontend can adopt the new address. The contract has been kept intentionally simple and straightforward to avoid potential attacks. */ contract EtherSign is Pausable { /*** EVENTS ***/ // @dev Again we don't store much outside of what is light and absolute neccessary in storage due to cost. Most data we try to manage via event firing // @dev Document related events. All events are kept intentionally similar orders as when searching for events we utilize topics and argument order matters. event DocumentSigned(address indexed signer, address indexed delegate, uint indexed documentId, string title, string content, uint64 time); event SignerAdded(address indexed signer, address indexed delegate, uint indexed documentId, uint64 time); // @dev Signing authority related events event Authorized(address indexed signer, address indexed delegate, uint64 time); event Deauthorized(address indexed signer, address indexed delegate, uint64 time); // @dev A straightforward mappin to keep track of authorized signers mapping (address => address) authorizedDelegates; // @dev We keep an internal document counter which is basically the document ID per se on the blockchain. This way we can later retrieve the doc by searching for the event with the id uint public documentCounter; /** @dev Mark a document signed by an address by firing approriate event. * @param _title The title of the document. * @param _content A LZMA compressed base64 string that can be decompressed to a fully styled document. * @param _signer Address of the person (or any capable intelligent being - AI, the matrix etc) who is signing the document. */ function signDocument(string _title, string _content, address _signer) external whenNotPaused { address delegate = authorizedDelegates[_signer]; // only the sender or an authorized delegate can sign on the sender behalf require((msg.sender == _signer) || (msg.sender == delegate)); // we will increment the document counter so it can act as an unique ID for the document that we can use later to retrieve document. documentCounter ++; // if the signer is acting on his/her own behalf, set the delegate to address 0 // if an authorized delegate is acting on the signer's behalf, mark it so on the event so we can distinguish who initiated the signing. if (msg.sender == _signer) { emit DocumentSigned(msg.sender, address(0), documentCounter, _title, _content, uint64(now)); } else if (msg.sender == delegate) { emit DocumentSigned(_signer, delegate, documentCounter, _title, _content, uint64(now)); } } /** @dev Add additional signatures to an existing document. * @notice When multiple users need to sign the same document (such as the US declaration of independence, to avoid user creating the same document multiple times, they should be able to simply add their signature for an existing doc. * @param _documentId The documentId assigned when the document was signed for the first time. * @param _signer Address of the person who is signing the document. */ function addSigner(uint _documentId, address _signer) external whenNotPaused { // contract need to exist require(_documentId <= documentCounter); address delegate = authorizedDelegates[_signer]; // only the sender or an authorized delegate can sign on the sender behalf require((msg.sender == _signer) || (msg.sender == delegate)); // if the signer is acting on his/her own behalf, set the delegate to address 0 // if an authorized delegate is acting on the signer's behalf, mark it so on the event so we can distinguish who initiated the signing. if (msg.sender == _signer) { emit SignerAdded(msg.sender, address(0), _documentId, uint64(now)); } else if (msg.sender == delegate) { emit SignerAdded(_signer, delegate, _documentId, uint64(now)); } } /** @dev We allow an account to authorize 1 other account to sign document on their behalf. Think of it like Power of Attorney etc. * @param _delegate The address of the account that you authorize full signing power for you. */ function authorize(address _delegate) external whenNotPaused { // You cannot set yourself, address 0 or existing delegate as your delegate, no need to waste gas on that. require(_delegate != msg.sender); require(_delegate != address(0)); address lastDelegate = authorizedDelegates[msg.sender]; require(_delegate != lastDelegate); if (lastDelegate != _delegate) { authorizedDelegates[msg.sender] = _delegate; // We need to fire events approriatly for real accounts (not for address 0) since we use events to track all the signers a delegate is responsible for. if (lastDelegate != address(0)) { emit Deauthorized(msg.sender, lastDelegate, uint64(now)); } emit Authorized(msg.sender, _delegate, uint64(now)); } } /** @dev Remove a previous delegate one have previous assigned. Note here we allow this method to be fired even when the contract is not paused as users should be able to retract in all circumstances. */ function deauthorize() external { if (authorizedDelegates[msg.sender] != address(0)) { address delegate = authorizedDelegates[msg.sender]; delete authorizedDelegates[msg.sender]; emit Deauthorized(msg.sender, delegate, uint64(now)); } } /** @dev Look up delegate who has signing power for a known address. * @param _signer The signer address we want to look up for. * @return address The signing delegate for the inquired address. */ function getDelegate(address _signer) external view returns (address) { return authorizedDelegates[_signer]; } /** @dev Check if an address has signing power for an address. Another convinience method to check signing power. * @param _signer The signer address we want to look up for. * @param _delegate The delegate address we want to look up for. * @return boolean Whether or not the inquired delegate address has signing power for the signer address. */ function isDelegate(address _signer, address _delegate) external view returns (bool) { address delegate = authorizedDelegates[_signer]; // We do not consider address 0 as delegate for anyone as that is the default value and theoretically no one should have access to address 0 account. if (delegate == address(0)) { return false; } else { return (delegate == _delegate); } } }
* @dev We allow an account to authorize 1 other account to sign document on their behalf. Think of it like Power of Attorney etc. @param _delegate The address of the account that you authorize full signing power for you./ You cannot set yourself, address 0 or existing delegate as your delegate, no need to waste gas on that. We need to fire events approriatly for real accounts (not for address 0) since we use events to track all the signers a delegate is responsible for.
function authorize(address _delegate) external whenNotPaused { require(_delegate != msg.sender); require(_delegate != address(0)); address lastDelegate = authorizedDelegates[msg.sender]; require(_delegate != lastDelegate); if (lastDelegate != _delegate) { authorizedDelegates[msg.sender] = _delegate; if (lastDelegate != address(0)) { emit Deauthorized(msg.sender, lastDelegate, uint64(now)); } emit Authorized(msg.sender, _delegate, uint64(now)); } }
2,556,300
[ 1, 3218, 1699, 392, 2236, 358, 12229, 404, 1308, 2236, 358, 1573, 1668, 603, 3675, 12433, 6186, 18, 935, 754, 434, 518, 3007, 23783, 434, 6020, 14245, 402, 5527, 18, 225, 389, 22216, 1021, 1758, 434, 326, 2236, 716, 1846, 12229, 1983, 10611, 7212, 364, 1846, 18, 19, 4554, 2780, 444, 3433, 2890, 16, 1758, 374, 578, 2062, 7152, 487, 3433, 7152, 16, 1158, 1608, 358, 341, 14725, 16189, 603, 716, 18, 1660, 1608, 358, 4452, 2641, 595, 86, 280, 77, 270, 715, 364, 2863, 9484, 261, 902, 364, 1758, 374, 13, 3241, 732, 999, 2641, 358, 3298, 777, 326, 1573, 414, 279, 7152, 353, 14549, 364, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 12229, 12, 2867, 389, 22216, 13, 3903, 1347, 1248, 28590, 288, 203, 565, 2583, 24899, 22216, 480, 1234, 18, 15330, 1769, 203, 565, 2583, 24899, 22216, 480, 1758, 12, 20, 10019, 203, 565, 1758, 1142, 9586, 273, 10799, 15608, 815, 63, 3576, 18, 15330, 15533, 203, 565, 2583, 24899, 22216, 480, 1142, 9586, 1769, 203, 203, 565, 309, 261, 2722, 9586, 480, 389, 22216, 13, 288, 203, 1377, 10799, 15608, 815, 63, 3576, 18, 15330, 65, 273, 389, 22216, 31, 203, 203, 1377, 309, 261, 2722, 9586, 480, 1758, 12, 20, 3719, 288, 203, 3639, 3626, 1505, 8434, 12, 3576, 18, 15330, 16, 1142, 9586, 16, 2254, 1105, 12, 3338, 10019, 203, 1377, 289, 203, 203, 1377, 3626, 6712, 1235, 12, 3576, 18, 15330, 16, 389, 22216, 16, 2254, 1105, 12, 3338, 10019, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xe7f4e16CE3974FC0E9CBf80B22Ee3A715Ca245F4/sources/contracts/Contract.sol
to return an array of structs
contract Wallet { address[] private approvers; uint public quorum; struct Transfer { uint id; uint amount; address payable to; uint approver; bool sent; } Transfer[] private transfers; uint public nextId; uint public currentId; mapping(address => mapping(uint => bool)) private approvals; mapping(address => uint) private checkId; constructor (address[] memory _approvers, uint _quorum) { approvers = _approvers; quorum = _quorum; } function createTransfer (uint _amount, address payable _to) onlyApprover external { transfers.push(Transfer( transfers.length, _amount, _to, 0, false )); nextId++; } function approveTransfer (uint id) onlyApprover external{ require(transfers[id].sent == false, "Transfer has already been sent"); require(approvals[msg.sender][id] == false, "Cannot approve transfer twice"); approvals[msg.sender][id] = true; transfers[id].approver++; if(transfers[id].approver >= quorum) { transfers[id].sent = true; address payable to = transfers[id].to; uint amount = transfers[id].amount; to.transfer(amount); } } function approveTransfer (uint id) onlyApprover external{ require(transfers[id].sent == false, "Transfer has already been sent"); require(approvals[msg.sender][id] == false, "Cannot approve transfer twice"); approvals[msg.sender][id] = true; transfers[id].approver++; if(transfers[id].approver >= quorum) { transfers[id].sent = true; address payable to = transfers[id].to; uint amount = transfers[id].amount; to.transfer(amount); } } receive() external payable {} modifier onlyApprover () { bool allowed = false; for (uint i = 0; i<approvers.length; i++) { if (approvers[i] == msg.sender) { allowed = true; } } require (allowed == true, 'only approver allowed'); _; } modifier onlyApprover () { bool allowed = false; for (uint i = 0; i<approvers.length; i++) { if (approvers[i] == msg.sender) { allowed = true; } } require (allowed == true, 'only approver allowed'); _; } modifier onlyApprover () { bool allowed = false; for (uint i = 0; i<approvers.length; i++) { if (approvers[i] == msg.sender) { allowed = true; } } require (allowed == true, 'only approver allowed'); _; } }
11,600,491
[ 1, 869, 327, 392, 526, 434, 8179, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 20126, 288, 203, 565, 1758, 8526, 3238, 6617, 2496, 31, 203, 565, 2254, 1071, 31854, 31, 203, 203, 203, 565, 1958, 12279, 288, 203, 565, 2254, 612, 31, 203, 565, 2254, 3844, 31, 203, 565, 1758, 8843, 429, 358, 31, 203, 565, 2254, 6617, 502, 31, 203, 565, 1426, 3271, 31, 203, 565, 289, 203, 565, 12279, 8526, 3238, 29375, 31, 203, 565, 2254, 1071, 1024, 548, 31, 203, 565, 2254, 1071, 783, 548, 31, 203, 377, 2874, 12, 2867, 516, 2874, 12, 11890, 516, 1426, 3719, 3238, 6617, 4524, 31, 203, 377, 2874, 12, 2867, 516, 2254, 13, 3238, 866, 548, 31, 203, 203, 565, 3885, 261, 2867, 8526, 3778, 389, 12908, 2496, 16, 2254, 389, 372, 16105, 13, 288, 203, 3639, 6617, 2496, 273, 389, 12908, 2496, 31, 203, 3639, 31854, 273, 389, 372, 16105, 31, 7010, 565, 289, 203, 203, 203, 203, 565, 445, 752, 5912, 261, 11890, 389, 8949, 16, 1758, 8843, 429, 389, 869, 13, 1338, 12053, 502, 3903, 288, 203, 3639, 29375, 18, 6206, 12, 5912, 12, 203, 5411, 29375, 18, 2469, 16, 203, 5411, 389, 8949, 16, 203, 5411, 389, 869, 16, 203, 5411, 374, 16, 203, 5411, 629, 203, 3639, 262, 1769, 203, 3639, 1024, 548, 9904, 31, 203, 565, 289, 203, 377, 445, 6617, 537, 5912, 261, 11890, 612, 13, 1338, 12053, 502, 3903, 95, 203, 540, 2583, 12, 2338, 18881, 63, 350, 8009, 7569, 422, 629, 16, 315, 5912, 711, 1818, 2118, 3271, 8863, 203, 540, 2583, 12, 12908, 4524, 63, 3576, 18, 2 ]
pragma solidity ^0.4.21; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract DAX { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; 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 DAX( ) public { totalSupply = 200000000000000000000000000; // Total supply with the decimal amount balanceOf[msg.sender] = 200000000000000000000000000; // All initial tokens name = "DAX Coin"; // The name for display purposes symbol = "DAX"; // 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; } }
Public variables of the token This creates an array with all balances This generates a public event on the blockchain that will notify clients This notifies clients about the amount burnt
contract DAX { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); function DAX( interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } ) public { } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } 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; } } 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; } } function burn(uint256 _value) public returns (bool success) { Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { Burn(_from, _value); return true; } }
14,877,311
[ 1, 4782, 3152, 434, 326, 1147, 1220, 3414, 392, 526, 598, 777, 324, 26488, 1220, 6026, 279, 1071, 871, 603, 326, 16766, 716, 903, 5066, 7712, 1220, 19527, 7712, 2973, 326, 3844, 18305, 88, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 463, 2501, 288, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 28, 1071, 15105, 273, 6549, 31, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 1071, 1699, 1359, 31, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 605, 321, 12, 2867, 8808, 628, 16, 2254, 5034, 460, 1769, 203, 203, 565, 445, 463, 2501, 12, 203, 5831, 1147, 18241, 288, 445, 6798, 23461, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 16, 1758, 389, 2316, 16, 1731, 389, 7763, 751, 13, 1071, 31, 289, 203, 565, 262, 1071, 288, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 1132, 13, 2713, 288, 203, 3639, 2583, 24899, 869, 480, 374, 92, 20, 1769, 203, 3639, 2583, 12, 12296, 951, 63, 67, 2080, 65, 1545, 389, 1132, 1769, 203, 3639, 2583, 12, 12296, 951, 63, 67, 869, 65, 397, 389, 1132, 405, 11013, 951, 63, 67, 869, 19226, 203, 3639, 2254, 2416, 38, 26488, 273, 11013, 951, 63, 67, 2080, 65, 397, 11013, 951, 63, 67, 869, 15533, 203, 3639, 11013, 951, 63, 67, 2080, 65, 3947, 389, 1132, 31, 203, 3639, 11013, 951, 63, 67, 869, 65, 1011, 389, 1132, 31, 203, 3639, 2 ]
/** *Submitted for verification at BscScan.com on 2021-10-18 */ // SPDX-License-Identifier: GPL-3.0 /** * @Author Vron */ pragma solidity >=0.7.0 <0.9.0; contract context { mapping(address => bool) private admins; event AddAdmin(address indexed _address, bool decision); event RemoveAdmin(address indexed _address, bool decision); address private _owner; // restricts access to only owner modifier onlyOwner() { require(msg.sender == _owner, "Only owner allowed."); _; } // restricts access to only admins modifier onlyAdmin() { require(admins[msg.sender] == true, "Only admins allowed."); _; } constructor(){ _owner = msg.sender; admins[msg.sender] = true; } // function returns contract owner function getOwner() public view returns (address) { return _owner; } function addAdmin(address _address) public { _addAdmin(_address, true); } // sets an admin function _addAdmin(address _address, bool _decision) private onlyOwner returns (bool) { require(_address != _owner, "Owner already added."); admins[_address] = _decision; emit AddAdmin(_address, _decision); return true; } function removeAdmin(address _address) public { _removeAdmin(_address, false); } // removes an admin function _removeAdmin(address _address, bool _decision) private onlyOwner returns (bool) { require(_address != _owner, "Owner cannot be removed."); admins[_address] = _decision; emit RemoveAdmin(_address, _decision); return true; } } /** * SafeMath * Math operations with safety checks that throw on error */ 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 1; } 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; } } interface BUSD { function balanceOf(address _address) external returns (uint256); function transfer(address _address, uint256 value) external returns (bool); function transferFrom(address _sender, address recipient, uint256 value) external returns (bool); } interface BETS { function balanceOf(address _address) external returns (uint256); function transfer(address _address, uint256 value) external returns (bool); function transferFrom(address _sender, address recipient, uint256 value) external returns (bool); } contract BetswampMVP is context { using SafeMath for uint256; // mapping stores event sub-category mapping(Category => string[]) private sub_category; // mapping stores sub-category index mapping(string => uint256) private category_index; // mapping maps event to its index in allActiveEvent mapping(uint256 => uint256) private event_index; // [eventID][MSG.SENDER] = true or false determines if user betted on an event mapping (uint256 => mapping (address => bool)) private bets; // [eventID] = true or false - determines if a BetEvent is still active mapping (uint256 => bool) private activeEvents; // maps an event to its record mapping (uint256 => BetEvent) private events; // maps an event and a bettor to bettors bets information [eventID][msg.sender] mapping (uint256 => mapping (address => Betted)) private userBets; // maps bet event occurrence to the number of users who selected it mapping (uint256 => mapping (Occurences => address[])) private eventBetOccurenceCount; // maps bet event occurence and the amount betted on it mapping (uint256 => mapping (Occurences => uint256)) private eventBetOccurenceAmount; // maps an event to the occurence that won after validation mapping (uint256 => Occurences) private occuredOccurrence; // maps a user to all their bets mapping (address => BetEvent[]) private userBetHistory; // maps a user to the number of their bets mapping (address => uint256[]) private userBetCounts; // map indicates if user locked funds for validation point mapping (address => bool) private _lock_validator_address; // map sets wallet lock time mapping (address => uint) private _validator_wallet_lock_time; // maps amount user locked mapping (address => uint256) private _validator_lock_amount; // maps user wallet to points earned mapping (address => uint256) private _wallet_validation_points; ///////////////////////////////////// // maps a validator to an event - used in checking if a validator validated an event mapping (address => mapping (uint256 => bool)) private validatorValidatedEvent; // maps a validator to the occurrence chosen mapping (uint256 => mapping (address => mapping (Occurences => bool))) private selectedValidationOccurrence; // maps an event and its occurence to validators that chose it mapping (uint256 => mapping (Occurences => address[])) private eventOccurenceValidators; // maps an event and a user to know if user has reclaimed the event's wager mapping (uint256 => mapping (address => bool)) private reclaimedBetWager; // maps an event to the amount lost in bet by bettors who choose the wrong event outcome mapping (uint256 => uint256) private amountLostInBet; // maps a bet event to validators who validated it mapping (uint256 => address[]) private eventValidators; // maps an event and a bettor to whether the reward has been claimed mapping (uint256 => mapping (address => bool)) private claimedReward; // maps an event to the divs for validators, system and all event bettors mapping (uint256 => Distribution) private divs; // maps an event to whether its crumbs have been withdrawn mapping (uint256 => bool) private hasTransferredCrumbs; // event is emitted when a validator validates an event event ValidateEvent(uint256 indexed eventID, Occurences occurence, address validator_address); //////////////////////////////////// // event emitted once event is created event CreateEvent(uint256 indexed event_id, Category category, string sub_category, string eventName, uint256 pool_size, uint256 eventTime, string eventOne, string eventTwo, address betCreator); // event emitted when a wager is made event PlaceBet(uint256 indexed event_id, address bettor_address, uint256 amount, Occurences occured); // event emitted when a user claims bet reward/winnings event Claim(address indexed user_address, uint256 _amount); /** * @dev WIN = 0, LOOSE = 1, LOOSE_OR_WIN = 2 and INVALID = 3 * On the client side, the user is only to see the follwoing * {WIN}, {LOOSE}, {DRAW} */ enum Occurences{WIN, LOOSE, LOOSE_OR_WIN, INVALID, UNKNOWN} // possible bet outcome enum Category{SPORTS, WEATHER, REALITY_TV_SHOWS, POLITICS, ENTERTAINMENT_AWARDS, DEAD_POOL, NOBEL_PRIZE, FUTURE_BET, OTHERS} // event categories /** * @dev stores Betevent information * * Requirement: * event creator must be an admin */ struct BetEvent { uint256 eventID; Category categories; string sub_category; string eventName; uint256 poolSize; // size of event pool uint256 startTime; // time event will occur uint256 endTime; string eventOne; // eventOne vs string eventTwo; //eventTwo bool validated; // false if event is not yet validated uint256 validatorsNeeded; Occurences occured; uint256 bettorsCount; uint256 noOfBettorsRewarded; uint256 amountClaimed; address betCreator; } /** * @dev stores user bet records * bettor balance must be greater or equal to 0 */ struct Betted { uint eventID; address bettorAddress; uint256 amount; Occurences occurence; } struct Distribution { uint256 bettorsDiv; } // wrapped BUSD mainnet: 0xe9e7cea3dedca5984780bafc599bd69add087d56 // wrapped BUSD testnet: 0x1d566540f39fd80cb2680461c8cf10bccc2a6fa1 BUSD private BUSD_token; BETS private BETS_token; bool private platformStatus; BetEvent[] private _event_id; BetEvent[] allActiveEvent; // list of active events uint256[] private validatedEvent; // list of validated events uint256 private totalAmountBetted; // total amount that has been betted on the platform uint256 private totalAmountClaimed; // total amount claimed on the platform // used to check if platform is active modifier isPlatformActive() { require(platformStatus == false, "Platfrom activity paused."); _; } /** * @dev modifier ensures user can only select WIN, LOOSE or LOOSE_OR_WIN * as the occurence they wager on or pick as occured occurence (for validators) */ modifier isValidOccurence(Occurences chosen) { require(chosen == Occurences.WIN || chosen == Occurences.LOOSE || chosen == Occurences.LOOSE_OR_WIN, "Invalid occurence selected."); _; } /** * @dev modifier check if a user has already claimed their bet reward */ modifier hasClaimedReward(uint256 event_id) { // check if user betted if (bets[event_id][msg.sender] == true) { // checks if user claimed reward require(claimedReward[event_id][msg.sender] == false, "Reward already claimed."); _; } else { revert("You have no stake on event."); } } /** * @dev modifier hinders validators from Validating * events that do not have opposing bets. */ modifier hasOpposingBets(uint256 event_id) { if (eventBetOccurenceCount[event_id][Occurences.WIN].length != 0 && eventBetOccurenceCount[event_id][Occurences.LOOSE].length != 0) { _; } else if (eventBetOccurenceCount[event_id][Occurences.WIN].length != 0 && eventBetOccurenceCount[event_id][Occurences.LOOSE_OR_WIN].length != 0) { _; } else if (eventBetOccurenceCount[event_id][Occurences.LOOSE].length != 0 && eventBetOccurenceCount[event_id][Occurences.LOOSE_OR_WIN].length != 0) { _; } else { revert("Validating events with none opposing bets not allowed."); } } constructor(address busd_token, address bets_token) { BUSD_token = BUSD(address(busd_token)); BETS_token = BETS(address(bets_token)); } // function adds sub-category function addSubbCategory(Category _category, string memory _sub_category) public onlyAdmin returns (bool) { sub_category[_category].push(_sub_category); category_index[_sub_category] = sub_category[_category].length - 1; return true; } // function removes a sub-category function removeSubCategory(Category _category, string memory _sub_category) public onlyAdmin returns (bool) { uint256 index = category_index[_sub_category]; sub_category[_category][index] = sub_category[_category][sub_category[_category].length - 1]; sub_category[_category].pop(); return true; } // function shows event category function getSubCategory(Category _category) public view returns (string[] memory) { return sub_category[_category]; } // create even function createEvent(Category _category, string memory _sub_category, string memory _name, uint256 _time, uint256 _endTime, string memory _event1, string memory _event2) public returns (bool) { _createEvent(_category,_sub_category, _name,_time,_endTime, _event1, _event2, msg.sender); return true; } // function creates betting event function _createEvent(Category _category, string memory _sub_category, string memory _name, uint256 _time, uint256 _endTime, string memory _event1, string memory _event2, address _creator) private onlyAdmin isPlatformActive returns (bool) { // ensure eventTime is greater current timestamp require(_time > block.timestamp, "Time of event must be greater than current time"); events[_event_id.length] = BetEvent(_event_id.length, _category,_sub_category, _name, 0, _time,_endTime, _event1, _event2, false, 3, Occurences.UNKNOWN, 0, 0, 0, _creator); // create event activeEvents[_event_id.length] = true; // set event as active allActiveEvent.push(events[_event_id.length]); // add event to active event list event_index[_event_id.length] = allActiveEvent.length - 1; _event_id.push(events[_event_id.length]); // increment number of events created emit CreateEvent(_event_id.length - 1, _category, _sub_category, _name, 0, _time, _event1, _event2, _creator); return true; } // function places bet function placeBet(uint256 event_id, uint256 _amount, Occurences _occured) public returns (bool) { _placeBet(event_id, _amount, _occured, msg.sender); return true; } // function places a bet function _placeBet(uint256 event_id, uint256 _amount, Occurences _occurred, address _bettor) private isPlatformActive returns (bool) { // check require(BUSD_token.balanceOf(_bettor) >= _amount, "Insufficient balance."); // check if bet event date has passed require(events[event_id].startTime >= block.timestamp, "You're not allowed to bet on elapsed or null events"); // check if event exist and is active require(activeEvents[event_id] == true, "Betting on none active bet events is not allowed."); BetEvent storage newEvent = events[event_id]; // get event details // check if user already Betted - increase betted amount on previous bet if (bets[event_id][msg.sender] == true) { // user already betted on event - increase stake on already placed bet BUSD_token.transferFrom(_bettor, address(this), _amount); userBets[event_id][msg.sender].amount = userBets[event_id][msg.sender].amount.add(_amount); eventBetOccurenceAmount[event_id][_occurred] = eventBetOccurenceAmount[event_id][_occurred].add(_amount); // increment the amount betted on the occurence newEvent.poolSize = newEvent.poolSize.add(_amount); // update pool amount _incrementTotalAmountBetted(_amount); // increment amount betted on platform return true; } BUSD_token.transferFrom(_bettor, address(this), _amount); addUserToOccurrenceBetCount(event_id, _occurred, _bettor); // increment number of users who betted on an event occurencece _incrementEventOccurrenceBetAmount(event_id, _occurred, _amount); // increment the amount betted on the occurence bets[event_id][_bettor] = true; // mark user as betted on event userBets[event_id][_bettor] = Betted(event_id, _bettor, _amount, _occurred); // place user bet newEvent.poolSize = newEvent.poolSize.add(_amount); // update pool amount newEvent.bettorsCount = newEvent.bettorsCount.add(1); // increment users that betted on the event addEventToUserHistory(newEvent); userBetCounts[_bettor].push(event_id); // increment number of events user has better on _incrementTotalAmountBetted(_amount); // increment amount betted on platform emit PlaceBet(event_id, _bettor, _amount, _occurred); return true; } // function gets users who selected a specific outcome for a betting event function getOccurrenceBetCount(uint256 event_id, Occurences _occured) public view returns (uint256) { return eventBetOccurenceCount[event_id][_occured].length; } // function adds a user to list of users who wagered on an event outcome function addUserToOccurrenceBetCount(uint256 event_id, Occurences _occurred, address _address) private { eventBetOccurenceCount[event_id][_occurred].push(_address); } // function gets amount wagered on a specific event occurrence function getEventOccurrenceBetAmount(uint256 event_id, Occurences _occurred) public view returns (uint256) { return eventBetOccurenceAmount[event_id][_occurred]; } // finction increments amount wagered on an event outcome function _incrementEventOccurrenceBetAmount(uint256 event_id, Occurences _occurred, uint256 _amount) private { eventBetOccurenceAmount[event_id][_occurred] = eventBetOccurenceAmount[event_id][_occurred].add(_amount); } // functions sets event occured occurrence after validation function setEventOccurredOccurrence(uint256 event_id, Occurences _occured) private { occuredOccurrence[event_id] = _occured; } // function gets event occurred occurrence after validation function getEventOccurredOccurrence(uint256 event_id) private view returns (Occurences) { return occuredOccurrence[event_id]; } // function remove event form active event list and puts it in validated event list function removeFromActiveEvents(uint256 event_id) private { // check if event is active require(activeEvents[event_id] == false, "Event not found."); allActiveEvent[event_index[event_id]] = allActiveEvent[allActiveEvent.length - 1]; allActiveEvent.pop(); } // function gets all active events function getActiveEvents() public view returns (BetEvent[] memory) { return allActiveEvent; } // function gets all validated event function getValidatedEvents() public view returns (uint256[] memory) { return validatedEvent; } // function get total betting event function totalEvents() public view returns (uint256) { return _event_id.length; } // function adds event to user bet history function addEventToUserHistory(BetEvent memory betEvent) private { userBetHistory[msg.sender].push(betEvent); } // function returns user bet histroy function getUserEventHistory() public view returns (BetEvent[] memory) { return userBetHistory[msg.sender]; } // function function _incrementTotalAmountBetted(uint256 _amount) private { totalAmountBetted = totalAmountBetted.add(_amount); } function claimValidationPoint() public returns (bool) { _calculateValidationPoint(); return true; } /** * @dev function calculates the users validation points * and rewards him his validation point. * function is triggered once user logs in */ function _calculateValidationPoint() internal { // check if wallet has any amount locked require(_lock_validator_address[msg.sender] == true, "Wallet don't earn points"); _wallet_validation_points[msg.sender] = _wallet_validation_points[msg.sender].add(_validator_lock_amount[msg.sender] * (block.timestamp - _validator_wallet_lock_time[msg.sender]) / 100000); // calculate point _validator_wallet_lock_time[msg.sender] = block.timestamp; // reset validation point timer } /** * @dev function displays user validation points */ function showValidationPoints() public view returns (uint256) { // return validationPoints return _wallet_validation_points[msg.sender]; } /** * @dev function rewards users validator rights through points. * * Requirement: user must have [amount] or more in wallet */ function earnValidationPoints(uint256 amount) public returns (bool) { _earnValidationPoints(msg.sender, amount); return true; } /** * @dev function rewards users validator rights through points. * * Requirement: user must have [amount] or more in wallet */ function _earnValidationPoints(address userAddress, uint256 amount) private isPlatformActive { // check if user balance greater or equal to amount require(BETS_token.balanceOf(userAddress) >= amount, "Insufficient balance."); // check if amount is zero => zero amount locking not allowed require(amount != 0, "Lockinng zero amount not allowed."); // check if user wallet is already earning points if ( _lock_validator_address[userAddress] == true && _validator_lock_amount[userAddress] != 0) { // wallect locked - check if amount specified matches balance after lock amount require((BETS_token.balanceOf(userAddress) -_validator_lock_amount[userAddress]) >= amount, "Insufficient balance."); BETS_token.transferFrom(userAddress, address(this), amount); // transfer funds to smart contract _validator_lock_amount[userAddress] = _validator_lock_amount[userAddress].add(amount); } else { // wallet not earning points - lock amount in wallet to earn points BETS_token.transferFrom(userAddress, address(this), amount); // transfer funds to smart contract _validator_wallet_lock_time[userAddress] = block.timestamp; // save user lock time _lock_validator_address[userAddress] = true; // user wallet locked _validator_lock_amount[userAddress] = amount; // user amount locked } } /** * @dev function renounces user point earning ability */ function revokeValidationPointsEarning() public { _revokeValidationPointsEarning(msg.sender); } /** * @dev function revokes user's ability to earn validation points */ function _revokeValidationPointsEarning(address userAddress) private { // claim user earned points and revoke user point earning _calculateValidationPoint(); // check if user is signed up for earning points require(_lock_validator_address[userAddress] == true && _validator_lock_amount[userAddress] != 0, "Wallet don't earn points."); // send locked amount back to user uint256 refund_amount = _validator_lock_amount[userAddress]; _validator_wallet_lock_time[userAddress] = 0; // reset user lock time _lock_validator_address[userAddress] = false; // user wallet unlocked _validator_lock_amount[userAddress] = 0; // reset locked amount to zero BETS_token.transfer(userAddress, refund_amount); // send user funds back to user } /** * @dev function returns the information * of a bet event and the number of bettors it has */ function getEvent(uint256 index) external view returns (BetEvent memory) { // check if bet event exist require(events[index].startTime > 0, "Bet event not found"); return events[index]; } /** * @dev function is used to validate an event * by validators. * * Requirements: * validator must have 1000 or more points * event validationElapseTime must not exceed block.timestamp. * eventTime must exceed block.timestamp */ function validateEvent(uint256 event_id, Occurences occurence) public returns (bool) { _validateEvent(event_id, occurence, msg.sender); return true; } /** * @dev function is used to validate an event * by validators. * * Requirements: * valdator must provide the event intended to be validated and the occurence that occured for the event * number of validators required to validate event must not have been exceeded * validator must have 1000 or more points * event validationElapseTime must not exceed block.timestamp. * eventTime must exceed block.timestamp * * Restriction: * validator cannot validate an event twice or more */ function _validateEvent(uint256 event_id, Occurences occurence, address validator_address) internal hasOpposingBets(event_id) isValidOccurence(occurence) isPlatformActive onlyAdmin { // check if event exist require(event_id <= _event_id.length, "Event not found."); // check if event has been validated require(events[event_id].validated == false, "Event validated."); // check if number of validators required to validate event has been exceeded require(eventValidators[event_id].length <= events[event_id].validatorsNeeded, "Number of validators needed reached."); // check if eventTime has been exceeded require(events[event_id].startTime < block.timestamp, "Event hasn't occured."); // check if event end time has reached require(events[event_id].endTime < block.timestamp, "Event not ready for validation."); // check if validator has validated event before require(validatorValidatedEvent[validator_address][event_id] == false, "Validating event twice not allowed."); // validator validates event eventOccurenceValidators[event_id][occurence].push(validator_address); // add validator to list of individuals that voted this occurence validatorValidatedEvent[validator_address][event_id] = true; // mark validator as validated event eventValidators[event_id].push(validator_address); // add validator to list of validators that validated event selectedValidationOccurrence[event_id][msg.sender][occurence] = true; emit ValidateEvent(event_id, occurence, validator_address); // emit ValidateEvent evet // 5 minutes to validation elapse time - check if event has 60% of required validators if ((events[event_id].validatorsNeeded / 100) * 70 >= eventValidators[event_id].length) { // event has 60% of needed validators _markAsValidated(event_id); // mark as validated _cummulateEventValidation(event_id); // cumulate validators event occurence vote // check if event occurred occurence isn't INVALID if (occuredOccurrence[event_id] != Occurences.INVALID) { _distributionFormular(event_id); // calculate divs } } if (eventValidators[event_id].length == events[event_id].validatorsNeeded) { // check if validators needed is filled - validated needed filed _markAsValidated(event_id); // mark as validated _cummulateEventValidation(event_id); // cumulate validators event occurence vote // check if event occurred occurence isn't INVALID if (occuredOccurrence[event_id] != Occurences.INVALID) { _distributionFormular(event_id); // calculate divs } } } /** * @dev function checks for the event occurence which * validators voted the most as the occured event * occurence. * Returns 0 if occurence is WIN * Returns 1 if occurence is LOOSE * Returns 2 if occurence is LOOSE_OR_WIN * Returns 3 if none of the above occurences won out. */ function _cummulateEventValidation(uint256 event_id) private { BetEvent storage event_occurrence = events[event_id]; // init betEvent instance // check the occurence that has the highest vote if (eventOccurenceValidators[event_id][Occurences.WIN].length > eventOccurenceValidators[event_id][Occurences.LOOSE].length && eventOccurenceValidators[event_id][Occurences.WIN].length > eventOccurenceValidators[event_id][Occurences.LOOSE_OR_WIN].length) { // set occured occurence occuredOccurrence[event_id] = Occurences.WIN; // set event occured occurence event_occurrence.occured = occuredOccurrence[event_id]; // assign amount to be shared amountLostInBet[event_id] = amountLostInBet[event_id].add(eventBetOccurenceAmount[event_id][Occurences.LOOSE] + eventBetOccurenceAmount[event_id][Occurences.LOOSE_OR_WIN]); } else if (eventOccurenceValidators[event_id][Occurences.LOOSE].length > eventOccurenceValidators[event_id][Occurences.WIN].length && eventOccurenceValidators[event_id][Occurences.LOOSE].length > eventOccurenceValidators[event_id][Occurences.LOOSE_OR_WIN].length) { occuredOccurrence[event_id] = Occurences.LOOSE; // set event occured occurence event_occurrence.occured = occuredOccurrence[event_id]; // assign amount to be shared amountLostInBet[event_id] = amountLostInBet[event_id].add(eventBetOccurenceAmount[event_id][Occurences.WIN] + eventBetOccurenceAmount[event_id][Occurences.LOOSE_OR_WIN]); } else if (eventOccurenceValidators[event_id][Occurences.LOOSE_OR_WIN].length > eventOccurenceValidators[event_id][Occurences.WIN].length && eventOccurenceValidators[event_id][Occurences.LOOSE_OR_WIN].length > eventOccurenceValidators[event_id][Occurences.LOOSE].length) { occuredOccurrence[event_id] = Occurences.LOOSE_OR_WIN; // set event occured occurence event_occurrence.occured = occuredOccurrence[event_id]; // assign amount to be shared amountLostInBet[event_id] = amountLostInBet[event_id].add(eventBetOccurenceAmount[event_id][Occurences.LOOSE] + eventBetOccurenceAmount[event_id][Occurences.WIN]); } else { occuredOccurrence[event_id] = Occurences.INVALID; // set event occured occurence event_occurrence.occured = occuredOccurrence[event_id]; } } /** * @dev function check if validator selected the * right event occurence reached through concensus */ function _isSelectedRightOccurrence(uint256 event_id) private view returns (bool) { // check if validator selected right event outcome if (selectedValidationOccurrence[event_id][msg.sender][occuredOccurrence[event_id]] == true) { // validator selected right event outcome return true; } // validator selected wrong event outcome return false; } /** * @dev function calculates the distribution of funds * after an event has been validated */ function _distributionFormular(uint256 event_id) private { // calculate what is left after winners reward has been removed uint256 winners_percent = (eventBetOccurenceAmount[event_id][occuredOccurrence[event_id]] * 100) / events[event_id].poolSize; uint256 winners_percent_remainder = ((eventBetOccurenceAmount[event_id][occuredOccurrence[event_id]] * 100) % events[event_id].poolSize) / 100; uint256 winners_reward = ((amountLostInBet[event_id] / 100) * winners_percent).add(winners_percent_remainder); uint256 div_amount = amountLostInBet[event_id].sub(winners_reward); Distribution storage setDivs = divs[event_id]; setDivs.bettorsDiv = setDivs.bettorsDiv.add(div_amount); } /** * @dev function is used in claiming reward */ function claimReward(uint256 event_id) external returns (bool) { _claimReward(event_id, msg.sender); return true; } /** * @dev function helps a user claim rewards * * Requirements: * [event_id] must be an event that has been validated * [msg.sender] must either be a bettor that participated in the event or validator * that validated the event */ function _claimReward(uint256 event_id, address user_address) private hasClaimedReward(event_id) { // check if event exist require(events[event_id].poolSize > 0, "Bet event not found"); // check if event occurrence is not UNKNOWN OR INVALID require(events[event_id].occured == Occurences.WIN || events[event_id].occured == Occurences.LOOSE || events[event_id].occured == Occurences.LOOSE_OR_WIN, "Reclaim wager instead."); // check if event has been validated require(events[event_id].validated == true, "Event not validated."); // check if user is a bettor of the event require(bets[event_id][user_address] == true, "You have no stake in this event."); BetEvent storage getEventDetails = events[event_id]; // user betted on event - check if user selected occured occurrence if (userBets[event_id][user_address].occurence == occuredOccurrence[event_id]) { // user selected occured occurrence - calculate user reward uint256 winners_percent = (userBets[event_id][user_address].amount * 100) / events[event_id].poolSize; uint256 winners_percent_remainder = ((userBets[event_id][user_address].amount * 100) % events[event_id].poolSize) / 100; uint256 user_reward = ((amountLostInBet[event_id] / 100) * winners_percent).add(winners_percent_remainder); user_reward = user_reward.add(userBets[event_id][user_address].amount); // refund user original bet amount user_reward = user_reward.add(divs[event_id].bettorsDiv / events[event_id].bettorsCount); // divide div amount by number of bettors - add amount to user reward claimedReward[event_id][user_address] = true; // user marked as collected reward _incrementTotalAmountClaimed(user_reward); // increment total amount claimed on platform getEventDetails.noOfBettorsRewarded = getEventDetails.noOfBettorsRewarded.add(1); // increment no. of event bettors rewarded getEventDetails.amountClaimed = getEventDetails.amountClaimed.add(user_reward); // increment event winnings claimed BUSD_token.transfer(user_address, user_reward); // transfer user reward to user emit Claim(user_address, user_reward); // emit claim event } else { // user chose wrong occurrence - reward user from div uint256 user_reward = divs[event_id].bettorsDiv / events[event_id].bettorsCount; claimedReward[event_id][user_address] = true; // user marked as collected reward _incrementTotalAmountClaimed(user_reward); // increment total amount claimed on platform getEventDetails.noOfBettorsRewarded = getEventDetails.noOfBettorsRewarded.add(1); // increment no. of event bettors rewarded getEventDetails.amountClaimed = getEventDetails.amountClaimed.add(user_reward); // increment event winnings claimed BUSD_token.transfer(user_address, user_reward); // transfer user reward to user emit Claim(user_address, user_reward); // emit claim event } } /** * @dev function marks an event as validated */ function _markAsValidated(uint256 event_id) private { BetEvent storage thisEvent = events[event_id]; // initialize event instance thisEvent.validated = true; activeEvents[event_id] = false; // set event as not active removeFromActiveEvents(event_id); // remove event from avalaibleEvents array validatedEvent.push(event_id); // add event to list of validated event } /** * @dev function increments the total winnings claimed * on the platform */ function _incrementTotalAmountClaimed(uint256 _value) private { totalAmountClaimed = totalAmountClaimed.add(_value); } /** * @dev function is used to pause almost all platform activities */ function pause() external onlyAdmin returns (bool) { // check if platform is paused if (platformStatus == true) { // platform paused - unpause platformStatus = false; return true; } else { // paltform not paused - pause platformStatus = true; return true; } } function currenctTime() external view returns (uint256) { return block.timestamp; } /** * @dev function withdraws funds left in smart contract after a particular * event winnings distribution. * This ensures funds are not mistakenly locked away in the smart contract * * REQUIREMENTS * [event_id] must an event that exist and is validated. * [event_id] must be an event in which all winnings have been distributed * [msg.sender] must be _owner */ function _transferCrumbs(uint256 event_id, address _address) private onlyOwner { // check if event has been validated require(events[event_id].validated == true, "Event not validated."); // check if all winnings have been distributed require(events[event_id].noOfBettorsRewarded == events[event_id].bettorsCount, "Winnings not distributed completely."); BetEvent memory eventDetails = events[event_id]; uint256 leftOverFunds = eventDetails.poolSize - eventDetails.amountClaimed; // funds left over after Winnings distribution BUSD_token.transfer(_address, leftOverFunds); } /** * @dev function withdraws funds left in smart contract after a particular * event winnings distribution. * This ensures funds are not mistakenly locked away in the smart contract * * REQUIREMENTS * [event_id] must an event that exist and is validated. * [event_id] must be an event in which all winnings have been distributed * [msg.sender] must be _owner */ function transferCrumbs(uint256 event_id, address _address) public returns (bool) { _transferCrumbs(event_id, _address); return true; } /** * @dev function is used to change the contract address * of BUSD and BETS */ function changeContractAddresses(address _busd, address _bet) public returns (bool) { BUSD_token = BUSD(address(_busd)); BETS_token = BETS(address(_bet)); return true; } }
* @dev stores user bet records bettor balance must be greater or equal to 0/
struct Betted { uint eventID; address bettorAddress; uint256 amount; Occurences occurence; }
15,810,329
[ 1, 19632, 729, 2701, 3853, 2701, 13039, 11013, 1297, 506, 6802, 578, 3959, 358, 374, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 605, 278, 2344, 288, 203, 3639, 2254, 871, 734, 31, 203, 3639, 1758, 2701, 13039, 1887, 31, 203, 3639, 2254, 5034, 3844, 31, 203, 3639, 531, 952, 18842, 764, 9145, 25267, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.20; contract EventsTest { event UpdateTestEvents( bytes32 indexed name, bytes32 indexed key, bytes32 indexed description); event DeleteTestEvents( bytes32 indexed name, bytes32 indexed key, int __DELETE__); bytes32 constant TABLE_EVENTS_TEST = "TEST_EVENTS"; struct Thing { string name; string description; bool exists; } int length; mapping(string => Thing) things; function addThing(string calldata _name, string calldata _description) external { Thing storage thing = things[_name]; if (!thing.exists) { length++; } thing.name = _name; thing.description = _description; thing.exists = true; emit UpdateTestEvents(prefix32(_name), TABLE_EVENTS_TEST, prefix32(_description)); } function addThings(string calldata _name, string calldata _description) external { Thing storage thing = things[_name]; if (!thing.exists) { length++; } thing.name = _name; thing.description = _description; thing.exists = true; emit UpdateTestEvents(prefix32(_name), TABLE_EVENTS_TEST, prefix32(_description)); emit UpdateTestEvents(prefix32(_name), TABLE_EVENTS_TEST, prefix32(_description)); } function removeThing(string calldata _name) external { Thing storage thing = things[_name]; if (thing.exists) { length--; delete things[_name]; emit DeleteTestEvents(prefix32(_name), TABLE_EVENTS_TEST, 0); } } function removeThings(string calldata _name) external { Thing storage thing = things[_name]; if (thing.exists) { length--; delete things[_name]; emit DeleteTestEvents(prefix32(_name), TABLE_EVENTS_TEST, 0); emit DeleteTestEvents(prefix32(_name), TABLE_EVENTS_TEST, 0); } } function count() external view returns (int size) { return length; } function description(string calldata _name) external view returns (string memory _description) { return things[_name].description; } function prefix32(string memory _str) private pure returns (bytes32 str32) { assembly { // We load one word256 after the start address of _str so that we get the first 32 bytes. Note: strings // with length less than 32 bytes are padded to a multiple of 32 bytes so we are not eating consecutive // memory here. str32 := mload(add(_str, 32)) } } }
We load one word256 after the start address of _str so that we get the first 32 bytes. Note: strings with length less than 32 bytes are padded to a multiple of 32 bytes so we are not eating consecutive memory here.
function prefix32(string memory _str) private pure returns (bytes32 str32) { assembly { str32 := mload(add(_str, 32)) } }
6,354,862
[ 1, 3218, 1262, 1245, 2076, 5034, 1839, 326, 787, 1758, 434, 389, 701, 1427, 716, 732, 336, 326, 1122, 3847, 1731, 18, 3609, 30, 2064, 598, 769, 5242, 2353, 3847, 1731, 854, 14426, 358, 279, 3229, 434, 3847, 1731, 1427, 732, 854, 486, 425, 1776, 18221, 3778, 2674, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1633, 1578, 12, 1080, 3778, 389, 701, 13, 3238, 16618, 1135, 261, 3890, 1578, 609, 1578, 13, 288, 203, 3639, 19931, 288, 203, 5411, 609, 1578, 519, 312, 945, 12, 1289, 24899, 701, 16, 3847, 3719, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x38509a9a014b6A9473f1602E5c14D3D196Fa7DDB/sources/contracts/GreedyGoblinsNFT.sol
The internal token ID tracker
contract GreedyGoblinsNFT is Ownable, ERC721Checkpointable, GreedyGoblinsLottery { using Counters for Counters.Counter; using Strings for uint256; address public winner; bool public saleIsActive = true; bool public presSaleIsActive = true; bool public isWhiteListActive = true; bool public LotteryIsActive = true; bool public revealed = false; string baseURI; string public baseExtension = ".json"; Counters.Counter private _tokenIdCounter; uint256 public constant MAX_SUPPLY = 10000; uint256 public constant MAX_PUBLIC_MINT = 10; uint256 public constant PRICE = 0.1 ether; uint256 public constant PreSale_Price = 0.01 ether; uint256 public constant WhiteList_PRICE = 0.001 ether; mapping(address => uint8) private _allowList; mapping(address => uint256) public _LotteryAllow; mapping(address => uint256) public _mintWhitelist; constructor() import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { ERC721Checkpointable } from "./ERC721Checkpointable.sol"; import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import { GreedyGoblinsLottery } from "./GreedyGoblinsLottery.sol"; ERC721("Greedy Goblins NFT", "GGNFT") { } function LotteryWinner(uint lottery) public returns (address payable) { winner = lotteryHistory[lottery]; _LotteryAllow[winner]=2; return lotteryHistory[lottery]; } function setIsWhiteListActive(bool _isWhiteListActive) external onlyOwner { isWhiteListActive = _isWhiteListActive; } function setWhiteList(address[] calldata addresses) external onlyOwner { uint8 numAllowedToMint = 3; uint256 WhiteListLength = addresses.length; for (uint256 i = 1; i < WhiteListLength; i++) { _allowList[addresses[i]] = numAllowedToMint; } } function setWhiteList(address[] calldata addresses) external onlyOwner { uint8 numAllowedToMint = 3; uint256 WhiteListLength = addresses.length; for (uint256 i = 1; i < WhiteListLength; i++) { _allowList[addresses[i]] = numAllowedToMint; } } function numAvailableToMint(address addr) external view returns (uint8) { return _allowList[addr]; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function reveal() public onlyOwner { revealed = true; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } 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 _mint(uint numberOfTokens) internal { uint256 ts = totalSupply(); require(saleIsActive, "Sale must be active to mint tokens"); require(numberOfTokens <= MAX_PUBLIC_MINT, "Exceeded max token purchase"); require(ts + numberOfTokens <= MAX_SUPPLY, "Purchase would exceed max tokens"); require(PRICE * numberOfTokens <= msg.value, "Ether value sent is not correct"); for (uint256 i = 1; i < numberOfTokens; i++) { _safeMint(msg.sender, ts + i); } } function _mint(uint numberOfTokens) internal { uint256 ts = totalSupply(); require(saleIsActive, "Sale must be active to mint tokens"); require(numberOfTokens <= MAX_PUBLIC_MINT, "Exceeded max token purchase"); require(ts + numberOfTokens <= MAX_SUPPLY, "Purchase would exceed max tokens"); require(PRICE * numberOfTokens <= msg.value, "Ether value sent is not correct"); for (uint256 i = 1; i < numberOfTokens; i++) { _safeMint(msg.sender, ts + i); } } function _presalemint(uint numberOfTokens) internal { uint256 ts = totalSupply(); require(presSaleIsActive, "PreSale must be active to mint tokens"); require(numberOfTokens <= MAX_PUBLIC_MINT, "Exceeded max token purchase"); require(ts + numberOfTokens <= MAX_SUPPLY, "Purchase would exceed max tokens"); require(PreSale_Price * numberOfTokens <= msg.value, "Ether value sent is not correct"); for (uint256 i = 1; i < numberOfTokens; i++) { _safeMint(msg.sender, ts + i); } } function _presalemint(uint numberOfTokens) internal { uint256 ts = totalSupply(); require(presSaleIsActive, "PreSale must be active to mint tokens"); require(numberOfTokens <= MAX_PUBLIC_MINT, "Exceeded max token purchase"); require(ts + numberOfTokens <= MAX_SUPPLY, "Purchase would exceed max tokens"); require(PreSale_Price * numberOfTokens <= msg.value, "Ether value sent is not correct"); for (uint256 i = 1; i < numberOfTokens; i++) { _safeMint(msg.sender, ts + i); } } function _mintWhiteList(uint8 numberOfTokens) internal { uint256 ts = totalSupply(); uint256 br = 1; require(isWhiteListActive, "Allow list is not active"); require(numberOfTokens <= 3, "Exceeded max available to purchase"); require(ts + numberOfTokens <= MAX_SUPPLY, "Purchase would exceed max tokens"); require(WhiteList_PRICE * numberOfTokens <= msg.value, "Ether value sent is not correct"); _allowList[msg.sender] -= numberOfTokens; for (uint256 i = 1; i < numberOfTokens; i++) { _safeMint(msg.sender, ts + i); br=i+1; } _mintWhitelist[msg.sender]=br; } function _mintWhiteList(uint8 numberOfTokens) internal { uint256 ts = totalSupply(); uint256 br = 1; require(isWhiteListActive, "Allow list is not active"); require(numberOfTokens <= 3, "Exceeded max available to purchase"); require(ts + numberOfTokens <= MAX_SUPPLY, "Purchase would exceed max tokens"); require(WhiteList_PRICE * numberOfTokens <= msg.value, "Ether value sent is not correct"); _allowList[msg.sender] -= numberOfTokens; for (uint256 i = 1; i < numberOfTokens; i++) { _safeMint(msg.sender, ts + i); br=i+1; } _mintWhitelist[msg.sender]=br; } function _mintLottery() internal { uint256 ts = totalSupply(); uint256 LotteryTokens = 2; require(_LotteryAllow[winner]==2); require(LotteryIsActive, "Allow list is not active"); require(ts + LotteryTokens <= MAX_SUPPLY, "Purchase would exceed max tokens"); require(msg.sender == winner, "Sender must be a winner of the lottery"); for (uint256 i = 1; i < LotteryTokens; i++) { _safeMint(msg.sender, ts + i); _LotteryAllow[winner]=1; } } function _mintLottery() internal { uint256 ts = totalSupply(); uint256 LotteryTokens = 2; require(_LotteryAllow[winner]==2); require(LotteryIsActive, "Allow list is not active"); require(ts + LotteryTokens <= MAX_SUPPLY, "Purchase would exceed max tokens"); require(msg.sender == winner, "Sender must be a winner of the lottery"); for (uint256 i = 1; i < LotteryTokens; i++) { _safeMint(msg.sender, ts + i); _LotteryAllow[winner]=1; } } function mintNFT(uint8 numberOfTokens) public payable { uint256 br = _allowList[msg.sender]; uint256 brNFT = balanceOf(msg.sender); require(brNFT+numberOfTokens<=10,"Maximum amount of Nft-s per account is 5"); if ( _LotteryAllow[winner]==2) { _mintLottery(); } else if((br!=1 && _mintWhitelist[msg.sender]+numberOfTokens<=3) && msg.value==WhiteList_PRICE*numberOfTokens ){ _mintWhiteList(numberOfTokens); } else if(presSaleIsActive) { _presalemint(numberOfTokens); } else { _mint(numberOfTokens); } } function mintNFT(uint8 numberOfTokens) public payable { uint256 br = _allowList[msg.sender]; uint256 brNFT = balanceOf(msg.sender); require(brNFT+numberOfTokens<=10,"Maximum amount of Nft-s per account is 5"); if ( _LotteryAllow[winner]==2) { _mintLottery(); } else if((br!=1 && _mintWhitelist[msg.sender]+numberOfTokens<=3) && msg.value==WhiteList_PRICE*numberOfTokens ){ _mintWhiteList(numberOfTokens); } else if(presSaleIsActive) { _presalemint(numberOfTokens); } else { _mint(numberOfTokens); } } function mintNFT(uint8 numberOfTokens) public payable { uint256 br = _allowList[msg.sender]; uint256 brNFT = balanceOf(msg.sender); require(brNFT+numberOfTokens<=10,"Maximum amount of Nft-s per account is 5"); if ( _LotteryAllow[winner]==2) { _mintLottery(); } else if((br!=1 && _mintWhitelist[msg.sender]+numberOfTokens<=3) && msg.value==WhiteList_PRICE*numberOfTokens ){ _mintWhiteList(numberOfTokens); } else if(presSaleIsActive) { _presalemint(numberOfTokens); } else { _mint(numberOfTokens); } } function mintNFT(uint8 numberOfTokens) public payable { uint256 br = _allowList[msg.sender]; uint256 brNFT = balanceOf(msg.sender); require(brNFT+numberOfTokens<=10,"Maximum amount of Nft-s per account is 5"); if ( _LotteryAllow[winner]==2) { _mintLottery(); } else if((br!=1 && _mintWhitelist[msg.sender]+numberOfTokens<=3) && msg.value==WhiteList_PRICE*numberOfTokens ){ _mintWhiteList(numberOfTokens); } else if(presSaleIsActive) { _presalemint(numberOfTokens); } else { _mint(numberOfTokens); } } function mintNFT(uint8 numberOfTokens) public payable { uint256 br = _allowList[msg.sender]; uint256 brNFT = balanceOf(msg.sender); require(brNFT+numberOfTokens<=10,"Maximum amount of Nft-s per account is 5"); if ( _LotteryAllow[winner]==2) { _mintLottery(); } else if((br!=1 && _mintWhitelist[msg.sender]+numberOfTokens<=3) && msg.value==WhiteList_PRICE*numberOfTokens ){ _mintWhiteList(numberOfTokens); } else if(presSaleIsActive) { _presalemint(numberOfTokens); } else { _mint(numberOfTokens); } } function setSaleState(bool newState) public onlyOwner { saleIsActive = newState; } function setPreSaleState(bool newPreSale) public onlyOwner { presSaleIsActive = newPreSale; } function setLotteryState(bool newLotteryState) public onlyOwner { LotteryIsActive = newLotteryState; } function safeMint(address to) public onlyOwner { _safeMint(to, _tokenIdCounter.current()); _tokenIdCounter.increment(); } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } }
12,403,134
[ 1, 1986, 2713, 1147, 1599, 9745, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 611, 15656, 93, 43, 947, 80, 2679, 50, 4464, 353, 14223, 6914, 16, 4232, 39, 27, 5340, 14431, 429, 16, 611, 15656, 93, 43, 947, 80, 2679, 48, 352, 387, 93, 288, 203, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 377, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 203, 565, 1758, 1071, 5657, 1224, 31, 203, 565, 1426, 1071, 272, 5349, 2520, 3896, 273, 638, 31, 203, 565, 1426, 1071, 4075, 30746, 2520, 3896, 273, 638, 31, 203, 565, 1426, 1071, 353, 13407, 682, 3896, 273, 638, 31, 203, 565, 1426, 1071, 511, 352, 387, 93, 2520, 3896, 273, 638, 31, 203, 377, 203, 565, 1426, 1071, 283, 537, 18931, 273, 629, 31, 203, 565, 533, 1026, 3098, 31, 203, 565, 533, 1071, 1026, 3625, 273, 3552, 1977, 14432, 203, 377, 203, 377, 203, 203, 565, 9354, 87, 18, 4789, 3238, 389, 2316, 548, 4789, 31, 203, 203, 377, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 13272, 23893, 273, 12619, 31, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 14939, 67, 49, 3217, 273, 1728, 31, 203, 565, 2254, 5034, 1071, 5381, 10365, 1441, 273, 374, 18, 21, 225, 2437, 31, 203, 565, 2254, 5034, 1071, 5381, 2962, 30746, 67, 5147, 273, 225, 374, 18, 1611, 225, 2437, 31, 203, 565, 2254, 5034, 1071, 5381, 30233, 682, 67, 7698, 1441, 273, 374, 18, 11664, 225, 2437, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 28, 13, 3238, 389, 5965, 682, 31, 203, 565, 2 ]
./full_match/1/0x40E5A14E1D151F34Fea6b8e6197c338e737f9Bf2/sources/contracts/exchange/VETHP2P.sol
VY_ETH market - converted selling amount in VY to ETH < MINIMUM_AUTOCLOSE_IN_ETH
bool takerCloseout = (tradingPair.takerAssetAddress == address(0) && _offers[seller][id].quantity * _offers[seller][id].price / MULTIPLIER < MINIMUM_AUTOCLOSE_IN_ETH);
8,498,055
[ 1, 58, 61, 67, 1584, 44, 13667, 300, 5970, 357, 2456, 3844, 316, 776, 61, 358, 512, 2455, 411, 6989, 18605, 67, 37, 1693, 10809, 9320, 67, 706, 67, 1584, 44, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1426, 268, 6388, 4605, 659, 273, 261, 313, 14968, 4154, 18, 88, 6388, 6672, 1887, 422, 1758, 12, 20, 13, 597, 389, 3674, 414, 63, 1786, 749, 6362, 350, 8009, 16172, 380, 389, 3674, 414, 63, 1786, 749, 6362, 350, 8009, 8694, 342, 31385, 2053, 654, 411, 6989, 18605, 67, 37, 1693, 10809, 9320, 67, 706, 67, 1584, 44, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xBAAA3053e773544561a119DB1F86985581D3fE7F/sources/contracts/stakerewardV2pool.sol
Immutable variables for staking and rewards tokens Duration of rewards to be paid out (in seconds) Timestamp of when the rewards finish Minimum of last updated time and reward finish time Reward to be paid out per second Sum of (reward rate * dt * 1e18 / total supply) User address => rewardPerTokenStored User address => rewards to be claimed Total staked User address => staked amount
contract StakingRewardsV2 { IERC20 public immutable stakingToken; IesLBR public immutable rewardsToken; IesLBRBoost public esLBRBoost; IlybraFund public lybraFund; address public owner; uint256 public duration = 2_592_000; uint256 public finishAt; uint256 public updatedAt; uint256 public rewardRate; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => uint256) public userUpdatedAt; uint256 public totalSupply; mapping(address => uint256) public balanceOf; constructor( address _stakingToken, address _rewardToken, address _boost, address _fund ) { owner = msg.sender; stakingToken = IERC20(_stakingToken); rewardsToken = IesLBR(_rewardToken); esLBRBoost = IesLBRBoost(_boost); lybraFund = IlybraFund(_fund); } modifier onlyOwner() { require(msg.sender == owner, "not authorized"); _; } modifier updateReward(address _account) { rewardPerTokenStored = rewardPerToken(); updatedAt = lastTimeRewardApplicable(); if (_account != address(0)) { rewards[_account] = earned(_account); userRewardPerTokenPaid[_account] = rewardPerTokenStored; userUpdatedAt[_account] = block.timestamp; } _; } modifier updateReward(address _account) { rewardPerTokenStored = rewardPerToken(); updatedAt = lastTimeRewardApplicable(); if (_account != address(0)) { rewards[_account] = earned(_account); userRewardPerTokenPaid[_account] = rewardPerTokenStored; userUpdatedAt[_account] = block.timestamp; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return _min(finishAt, block.timestamp); } function rewardPerToken() public view returns (uint256) { if (totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored + (rewardRate * (lastTimeRewardApplicable() - updatedAt) * 1e18) / totalSupply; } function rewardPerToken() public view returns (uint256) { if (totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored + (rewardRate * (lastTimeRewardApplicable() - updatedAt) * 1e18) / totalSupply; } function stake(uint256 _amount) external updateReward(msg.sender) { require(_amount > 0, "amount = 0"); stakingToken.transferFrom(msg.sender, address(this), _amount); balanceOf[msg.sender] += _amount; totalSupply += _amount; } function withdraw(uint256 _amount) external updateReward(msg.sender) { require(_amount > 0, "amount = 0"); balanceOf[msg.sender] -= _amount; totalSupply -= _amount; stakingToken.transfer(msg.sender, _amount); } function getBoost(address _account) public view returns (uint256) { return 100 * 1e18 + esLBRBoost.getUserBoost( _account, userUpdatedAt[_account], finishAt ); } function earned(address _account) public view returns (uint256) { return ((balanceOf[_account] * getBoost(_account) * (rewardPerToken() - userRewardPerTokenPaid[_account])) / 1e38) + rewards[_account]; } function getReward() external updateReward(msg.sender) { require( block.timestamp >= esLBRBoost.getUnlockTime(msg.sender), "Your lock-in period has not ended. You can't claim your esLBR now." ); uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; lybraFund.refreshReward(msg.sender); rewardsToken.mint(msg.sender, reward); } } function getReward() external updateReward(msg.sender) { require( block.timestamp >= esLBRBoost.getUnlockTime(msg.sender), "Your lock-in period has not ended. You can't claim your esLBR now." ); uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; lybraFund.refreshReward(msg.sender); rewardsToken.mint(msg.sender, reward); } } function setRewardsDuration(uint256 _duration) external onlyOwner { require(finishAt < block.timestamp, "reward duration not finished"); duration = _duration; } function setBoost(address _boost) external onlyOwner { esLBRBoost = IesLBRBoost(_boost); } function notifyRewardAmount(uint256 _amount) external onlyOwner updateReward(address(0)) { if (block.timestamp >= finishAt) { rewardRate = _amount / duration; uint256 remainingRewards = (finishAt - block.timestamp) * rewardRate; rewardRate = (_amount + remainingRewards) / duration; } require(rewardRate > 0, "reward rate = 0"); finishAt = block.timestamp + duration; updatedAt = block.timestamp; } function notifyRewardAmount(uint256 _amount) external onlyOwner updateReward(address(0)) { if (block.timestamp >= finishAt) { rewardRate = _amount / duration; uint256 remainingRewards = (finishAt - block.timestamp) * rewardRate; rewardRate = (_amount + remainingRewards) / duration; } require(rewardRate > 0, "reward rate = 0"); finishAt = block.timestamp + duration; updatedAt = block.timestamp; } } else { function _min(uint256 x, uint256 y) private pure returns (uint256) { return x <= y ? x : y; } }
17,119,150
[ 1, 16014, 3152, 364, 384, 6159, 471, 283, 6397, 2430, 4822, 434, 283, 6397, 358, 506, 30591, 596, 261, 267, 3974, 13, 8159, 434, 1347, 326, 283, 6397, 4076, 23456, 434, 1142, 3526, 813, 471, 19890, 4076, 813, 534, 359, 1060, 358, 506, 30591, 596, 1534, 2205, 9352, 434, 261, 266, 2913, 4993, 225, 3681, 225, 404, 73, 2643, 342, 2078, 14467, 13, 2177, 1758, 516, 19890, 2173, 1345, 18005, 2177, 1758, 516, 283, 6397, 358, 506, 7516, 329, 10710, 384, 9477, 2177, 1758, 516, 384, 9477, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 934, 6159, 17631, 14727, 58, 22, 288, 203, 565, 467, 654, 39, 3462, 1071, 11732, 384, 6159, 1345, 31, 203, 565, 467, 281, 48, 7192, 1071, 11732, 283, 6397, 1345, 31, 203, 565, 467, 281, 48, 7192, 26653, 1071, 5001, 48, 7192, 26653, 31, 203, 565, 467, 715, 15397, 42, 1074, 1071, 18519, 15397, 42, 1074, 31, 203, 565, 1758, 1071, 3410, 31, 203, 203, 565, 2254, 5034, 1071, 3734, 273, 576, 67, 6162, 22, 67, 3784, 31, 203, 565, 2254, 5034, 1071, 4076, 861, 31, 203, 565, 2254, 5034, 1071, 31944, 31, 203, 565, 2254, 5034, 1071, 19890, 4727, 31, 203, 565, 2254, 5034, 1071, 19890, 2173, 1345, 18005, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 729, 17631, 1060, 2173, 1345, 16507, 350, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 283, 6397, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 729, 20624, 31, 203, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 334, 6159, 1345, 16, 203, 3639, 1758, 389, 266, 2913, 1345, 16, 203, 3639, 1758, 389, 25018, 16, 203, 3639, 1758, 389, 74, 1074, 203, 565, 262, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 384, 6159, 1345, 273, 467, 654, 39, 3462, 24899, 334, 6159, 1345, 1769, 203, 3639, 283, 6397, 1345, 273, 467, 281, 48, 7192, 24899, 266, 2913, 1345, 1769, 2 ]
pragma solidity ^0.6.0; contract GasToken { ////////////////////////////////////////////////////////////////////////// // Generic ERC20 ////////////////////////////////////////////////////////////////////////// // owner -> amount mapping(address => uint256) s_balances; // owner -> spender -> max amount mapping(address => mapping(address => uint256)) s_allowances; event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); // Spec: Get the account balance of another account with address `owner` function balanceOf(address owner) public view returns (uint256 balance) { return s_balances[owner]; } function internalTransfer( address from, address to, uint256 value ) internal returns (bool success) { if (value <= s_balances[from]) { s_balances[from] -= value; s_balances[to] += value; emit Transfer(from, to, value); return true; } else { return false; } } // Spec: Send `value` amount of tokens to address `to` function transfer(address to, uint256 value) public returns (bool success) { address from = msg.sender; return internalTransfer(from, to, value); } // Spec: Send `value` amount of tokens from address `from` to address `to` function transferFrom( address from, address to, uint256 value ) public returns (bool success) { address spender = msg.sender; if ( value <= s_allowances[from][spender] && internalTransfer(from, to, value) ) { s_allowances[from][spender] -= value; return true; } else { return false; } } // Spec: Allow `spender` to withdraw from your account, multiple times, up // to the `value` amount. If this function is called again it overwrites the // current allowance with `value`. function approve(address spender, uint256 value) public returns (bool success) { address owner = msg.sender; if (value != 0 && s_allowances[owner][spender] != 0) { return false; } s_allowances[owner][spender] = value; emit Approval(owner, spender, value); return true; } // Spec: Returns the `amount` which `spender` is still allowed to withdraw // from `owner`. // What if the allowance is higher than the balance of the `owner`? // Callers should be careful to use min(allowance, balanceOf) to make sure // that the allowance is actually present in the account! function allowance(address owner, address spender) public view returns (uint256 remaining) { return s_allowances[owner][spender]; } ////////////////////////////////////////////////////////////////////////// // GasToken specifics ////////////////////////////////////////////////////////////////////////// uint8 public constant decimals = 2; string public constant name = "Gastoken.io"; string public constant symbol = "GST1"; // We start our storage at this location. The EVM word at this location // contains the number of stored words. The stored words follow at // locations (STORAGE_LOCATION_ARRAY+1), (STORAGE_LOCATION_ARRAY+2), ... uint256 constant STORAGE_LOCATION_ARRAY = 0xDEADBEEF; // totalSupply is the number of words we have in storage function totalSupply() public view returns (uint256 supply) { uint256 storage_location_array = STORAGE_LOCATION_ARRAY; assembly { supply := sload(storage_location_array) } } // Mints `value` new sub-tokens (e.g. cents, pennies, ...) by filling up // `value` words of EVM storage. The minted tokens are owned by the // caller of this function. function mint(uint256 value) public { uint256 storage_location_array = STORAGE_LOCATION_ARRAY; // can't use constants inside assembly if (value == 0) { return; } // Read supply uint256 supply; assembly { supply := sload(storage_location_array) } // Set memory locations in interval [l, r] uint256 l = storage_location_array + supply + 1; uint256 r = storage_location_array + supply + value; assert(r >= l); for (uint256 i = l; i <= r; i++) { assembly { sstore(i, 1) } } // Write updated supply & balance assembly { sstore(storage_location_array, add(supply, value)) } s_balances[msg.sender] += value; } function freeStorage(uint256 value) internal { uint256 storage_location_array = STORAGE_LOCATION_ARRAY; // can't use constants inside assembly // Read supply uint256 supply; assembly { supply := sload(storage_location_array) } // Clear memory locations in interval [l, r] uint256 l = storage_location_array + supply - value + 1; uint256 r = storage_location_array + supply; for (uint256 i = l; i <= r; i++) { assembly { sstore(i, 0) } } // Write updated supply assembly { sstore(storage_location_array, sub(supply, value)) } } // Frees `value` sub-tokens (e.g. cents, pennies, ...) belonging to the // caller of this function by clearing value words of EVM storage, which // will trigger a partial gas refund. function free(uint256 value) public returns (bool success) { uint256 from_balance = s_balances[msg.sender]; if (value > from_balance) { return false; } freeStorage(value); s_balances[msg.sender] = from_balance - value; return true; } // Frees up to `value` sub-tokens. Returns how many tokens were freed. // Otherwise, identical to free. function freeUpTo(uint256 value) public returns (uint256 freed) { uint256 from_balance = s_balances[msg.sender]; if (value > from_balance) { value = from_balance; } freeStorage(value); s_balances[msg.sender] = from_balance - value; return value; } // Frees `value` sub-tokens owned by address `from`. Requires that `msg.sender` // has been approved by `from`. function freeFrom(address from, uint256 value) public returns (bool success) { address spender = msg.sender; uint256 from_balance = s_balances[from]; if (value > from_balance) { return false; } mapping(address => uint256) storage from_allowances = s_allowances[from]; uint256 spender_allowance = from_allowances[spender]; if (value > spender_allowance) { return false; } freeStorage(value); s_balances[from] = from_balance - value; from_allowances[spender] = spender_allowance - value; return true; } // Frees up to `value` sub-tokens owned by address `from`. Returns how many tokens were freed. // Otherwise, identical to `freeFrom`. function freeFromUpTo(address from, uint256 value) public returns (uint256 freed) { address spender = msg.sender; uint256 from_balance = s_balances[from]; if (value > from_balance) { value = from_balance; } mapping(address => uint256) storage from_allowances = s_allowances[from]; uint256 spender_allowance = from_allowances[spender]; if (value > spender_allowance) { value = spender_allowance; } freeStorage(value); s_balances[from] = from_balance - value; from_allowances[spender] = spender_allowance - value; return value; } }
Spec: Returns the `amount` which `spender` is still allowed to withdraw from `owner`. What if the allowance is higher than the balance of the `owner`? Callers should be careful to use min(allowance, balanceOf) to make sure that the allowance is actually present in the account!
function allowance(address owner, address spender) public view returns (uint256 remaining) { return s_allowances[owner][spender]; } uint8 public constant decimals = 2; string public constant name = "Gastoken.io"; string public constant symbol = "GST1";
14,061,166
[ 1, 1990, 30, 2860, 326, 1375, 8949, 68, 1492, 1375, 87, 1302, 264, 68, 353, 4859, 2935, 358, 598, 9446, 628, 1375, 8443, 8338, 18734, 309, 326, 1699, 1359, 353, 10478, 2353, 326, 11013, 434, 326, 1375, 8443, 68, 35, 3049, 414, 1410, 506, 26850, 358, 999, 1131, 12, 5965, 1359, 16, 11013, 951, 13, 358, 1221, 3071, 716, 326, 1699, 1359, 353, 6013, 3430, 316, 326, 2236, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 4463, 13, 203, 565, 288, 203, 3639, 327, 272, 67, 5965, 6872, 63, 8443, 6362, 87, 1302, 264, 15533, 203, 565, 289, 203, 203, 565, 2254, 28, 1071, 5381, 15105, 273, 576, 31, 203, 565, 533, 1071, 5381, 508, 273, 315, 43, 689, 969, 18, 1594, 14432, 203, 565, 533, 1071, 5381, 3273, 273, 315, 43, 882, 21, 14432, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; struct AirlineInfo { bool isRegistered; bool isFunded; string name; address[] approvedBy; } struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; string flight; address[] insuredPassengers; mapping(address => uint256) passengersPaymentAmount; } mapping(bytes32 => Flight) public flights; address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false uint256 public registeredAirlinesCount = 1; mapping(address => AirlineInfo) public airlines; mapping(address => uint256) public passengersBalances; mapping(address => bool) public authorizedContracts; mapping(address => uint256) public insurees; //address constant firstAirlineAddress = 0x954cB087C29cf91FDFfd6A144F2F7bBc8b87e1bA; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event FlightStatusUpdated(bytes32 flightKey, uint8 status, uint256 passengersCount); event AmountRefundedToPassengerBalance(address passenger, uint256 refundAmount); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( address firstAirlineAddress ) public { contractOwner = msg.sender; airlines[firstAirlineAddress] = AirlineInfo({ isRegistered: true, approvedBy: new address[](0), isFunded: false, name: 'Test Airlines' }); registeredAirlinesCount = 1; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireValidAddress(address account) { require(account != address(0), "'account' must be a valid address."); _; } // Only our app contract is allowed to call this data contract modifier requireAuthorizedCaller() { require(authorizedContracts[msg.sender] == true, "Call origin is not authorized to access this contract."); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } // Allow contract owner to add a list of authorized contracts function authorizeAppContract(address contractAddress) external requireIsOperational requireContractOwner { authorizedContracts[contractAddress] = true; } function isAirline( address airline ) external returns (bool) { return airlines[airline].isRegistered; } function getRegisteredAirlinesCount() external returns (uint256) { return registeredAirlinesCount; } function getAirlineInfo(address airline) external returns (bool isRegistered, bool isFunded, uint256 approvedByLength) { isRegistered = airlines[airline].isRegistered; isFunded = airlines[airline].isRegistered; approvedByLength = airlines[airline].approvedBy.length; } function getAirlineApprovalList(address airline) external returns (address[]) { return airlines[airline].approvedBy; } function getPassengerInsuredAmount(address airline, string flight, uint256 timestamp, address passenger) external returns (uint256) { bytes32 flightKey = getFlightKey(airline, flight, timestamp); return flights[flightKey].passengersPaymentAmount[passenger]; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address airline, string name ) external requireIsOperational requireValidAddress(airline) { airlines[airline].isRegistered = true; airlines[airline].name = name; registeredAirlinesCount = registeredAirlinesCount + 1; } function addToAirlineApprovalList(address airline, address approver) external { airlines[airline].approvedBy.push(approver); } /** * @dev Register a future flight for insuring. * */ function registerFlight ( string flight, address airline, uint256 timestamp ) external { require(!flights[flightKey].isRegistered, "Flight is already registered."); bytes32 flightKey = getFlightKey(airline, flight, timestamp); flights[flightKey] = Flight({ isRegistered: true, updatedTimestamp: timestamp, airline: airline, flight: flight, statusCode: STATUS_CODE_UNKNOWN, insuredPassengers: new address[](0) }); } function processFlightStatus ( bytes32 flightKey, uint8 statusCode ) external { Flight memory flight = flights[flightKey]; //require(flight.statusCode != statusCode, "Flight already processed"); require(flight.isRegistered, "Flight isn't registered"); //require(flight.statusCode == STATUS_CODE_UNKNOWN, "Flight isn't registered"); flights[flightKey].statusCode = statusCode; emit FlightStatusUpdated(flightKey, statusCode, flight.insuredPassengers.length); if (statusCode == 20) { creditInsurees(flightKey); } } /** * @dev Buy insurance for a flight * */ function buy ( bytes32 flightKey, address passenger ) external payable { require(flights[flightKey].isRegistered, "Flight isn't registered."); // require(flights[flightKey].passengersPaymentAmount[passenger] == 0, "Passenger can't insure multiple times for same airplane/flight"); flights[flightKey].passengersPaymentAmount[passenger] = uint256(msg.value); flights[flightKey].insuredPassengers.push(passenger); } /** * @dev Credits payouts to insurees */ function creditInsurees ( bytes32 flightKey ) internal { Flight flight = flights[flightKey]; require(flight.isRegistered, "Flight isn't registered."); for (uint a = 0; a < flight.insuredPassengers.length; a++) { address passenger = flight.insuredPassengers[a]; uint256 refundAmount = flights[flightKey].passengersPaymentAmount[passenger].mul(3).div(2); emit AmountRefundedToPassengerBalance(passenger, refundAmount); passengersBalances[passenger] = passengersBalances[passenger].add(refundAmount); } } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( address account ) external { require(passengersBalances[account] > 0, "No refund amount for this passenger"); uint256 value = passengersBalances[account]; passengersBalances[account] = 0; account.transfer(value); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( address airline ) public payable { airlines[airline].isFunded = true; } function getFlightKey ( address airline, string flight, uint256 timestamp ) pure public returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(tx.origin); } }
Only our app contract is allowed to call this data contract
modifier requireAuthorizedCaller() { require(authorizedContracts[msg.sender] == true, "Call origin is not authorized to access this contract."); _; }
7,226,828
[ 1, 3386, 3134, 595, 6835, 353, 2935, 358, 745, 333, 501, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 9606, 2583, 15341, 11095, 1435, 288, 203, 3639, 2583, 12, 8434, 20723, 63, 3576, 18, 15330, 65, 422, 638, 16, 315, 1477, 4026, 353, 486, 10799, 358, 2006, 333, 6835, 1199, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0xF206f9ACBE69CA5d2166a36F22d5D8e10f2d836D/sources/WOOL.sol
a mapping from an address to whether or not it can mint / burn
contract WOOL is ERC20, Ownable { mapping(address => bool) controllers; constructor() ERC20("aw", "aw") { } function mint(address to, uint256 amount) external { require(controllers[msg.sender], "Only controllers can mint"); _mint(to, amount); } function burn(address from, uint256 amount) external { require(controllers[msg.sender], "Only controllers can burn"); _burn(from, amount); } function addController(address controller) external onlyOwner { controllers[controller] = true; } function removeController(address controller) external onlyOwner { controllers[controller] = false; } }
4,635,444
[ 1, 69, 2874, 628, 392, 1758, 358, 2856, 578, 486, 518, 848, 312, 474, 342, 18305, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 678, 51, 1741, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 203, 225, 2874, 12, 2867, 516, 1426, 13, 12403, 31, 203, 21281, 203, 203, 225, 3885, 1435, 4232, 39, 3462, 2932, 2219, 3113, 315, 2219, 7923, 288, 289, 203, 225, 445, 312, 474, 12, 2867, 358, 16, 2254, 5034, 3844, 13, 3903, 288, 203, 565, 2583, 12, 20171, 63, 3576, 18, 15330, 6487, 315, 3386, 12403, 848, 312, 474, 8863, 203, 565, 389, 81, 474, 12, 869, 16, 3844, 1769, 203, 225, 289, 203, 203, 225, 445, 18305, 12, 2867, 628, 16, 2254, 5034, 3844, 13, 3903, 288, 203, 565, 2583, 12, 20171, 63, 3576, 18, 15330, 6487, 315, 3386, 12403, 848, 18305, 8863, 203, 565, 389, 70, 321, 12, 2080, 16, 3844, 1769, 203, 225, 289, 203, 203, 225, 445, 527, 2933, 12, 2867, 2596, 13, 3903, 1338, 5541, 288, 203, 565, 12403, 63, 5723, 65, 273, 638, 31, 203, 225, 289, 203, 203, 225, 445, 1206, 2933, 12, 2867, 2596, 13, 3903, 1338, 5541, 288, 203, 565, 12403, 63, 5723, 65, 273, 629, 31, 203, 225, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
(* NewVotingSystem.sol Created by Takumi Furusho on 2022/01/24 Copyright (c) 2022 Takumi Furusho *) pragma solidity ^0.8.11; contract NewVoting { //学生ストラクト struct Student { bool Orvoted; //投票したかどうか trueなら3回投票済み 初期値はfalse uint Weight; //投票回数 初期値は0 string VoteName; //投票先の候補者名 } //学生マッピング mapping(address => Student) public students; //教師 address public teacher; //候補者ストラクト struct Candidate { uint VotesReceived; //候補者の得票数 string Name; //候補者の名前 } //候補者リストマッピング Candidate[] public CandidateList; //構造体型の候補者リスト function CandidateFactory() public { //候補者を登録 //具体的な名前 得票数は初期値として0を与える CandidateList.push(Candidate(0, "Sato")); //リストに追加していく CandidateList.push(Candidate(0, "Takahashi")); CandidateList.push(Candidate(0, "Okamoto")); CandidateList.push(Candidate(0, "Tani")); CandidateList.push(Candidate(0, "Nakamura")); CandidateList.push(Candidate(0, "Tanaka")); CandidateList.push(Candidate(0, "Kato")); CandidateList.push(Candidate(0, "Matsumoto")); CandidateList.push(Candidate(0, "Ito")); CandidateList.push(Candidate(0, "Yamashita")); } //コンストラクタ function Vote() public { teacher = msg.sender; //教師を設定 } //教師が学生に投票権を与える function GiveRight(address student) public { require((msg.sender == teacher) && !students[student].Orvoted); //教師であることかつ学生が未投票であること students[student].Weight = 3; //投票権は1人3票 } //候補者名を記述して投票する   その後、得票数を昇順に並び替える function VoteForCandidate() public { address student1; //投票者1人目 GiveRight(student1); //投票権を受け取る //1回目の投票 students[student1].VoteName = "Takahashi"; require(ValidCandidate(student1)); //候補者リストにある名前かどうかチェック Remove("Takahashi"); //投票した候補者をリストから消す //2回目の投票 students[student1].VoteName = "Tani"; //上記の繰り返し require(ValidCandidate(student1)); Remove("Tani"); //3回目の投票 students[student1].VoteName = "Sato"; require(ValidCandidate(student1)); Remove("Sato"); CandidateList.push(Candidate(1, "Takahashi")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(1, "Tani")); CandidateList.push(Candidate(1, "Sato")); students[student1].Orvoted = true; //投票完了 address student2; //投票者2人目 GiveRight(student2); //投票権を受け取る //1回目の投票 students[student2].VoteName = "Yamashita"; require(ValidCandidate(student2)); //候補者リストにある名前かどうかチェック Remove("Yamashita"); //投票した候補者をリストから消す //2回目の投票 students[student2].VoteName = "Ito"; //上記の繰り返し require(ValidCandidate(student2)); Remove("Ito"); //3回目の投票 students[student2].VoteName = "Sato"; require(ValidCandidate(student2)); Remove("Sato"); CandidateList.push(Candidate(1, "Yamashita")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(1, "Ito")); CandidateList.push(Candidate(2, "Sato")); students[student2].Orvoted = true; //投票完了 address student3; //投票者3人目 GiveRight(student3); //投票権を受け取る //1回目の投票 students[student3].VoteName = "Tani"; require(ValidCandidate(student3)); //候補者リストにある名前かどうかチェック Remove("Tani"); //投票した候補者をリストから消す //2回目の投票 students[student3].VoteName = "Yamashita"; //上記の繰り返し require(ValidCandidate(student3)); Remove("Yamashita"); //3回目の投票 students[student3].VoteName = "Takahashi"; require(ValidCandidate(student3)); Remove("Takahashi"); CandidateList.push(Candidate(2, "Tani")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(2, "Yamashita")); CandidateList.push(Candidate(2, "Takahashi")); students[student3].Orvoted = true; //投票完了 address student4; //投票者4人目 GiveRight(student4); //投票権を受け取る //1回目の投票 students[student4].VoteName = "Ito"; require(ValidCandidate(student4)); //候補者リストにある名前かどうかチェック Remove("Ito"); //投票した候補者をリストから消す //2回目の投票 students[student4].VoteName = "Tani"; //上記の繰り返し require(ValidCandidate(student4)); Remove("Tani"); //3回目の投票 students[student4].VoteName = "Sato"; require(ValidCandidate(student4)); Remove("Sato"); CandidateList.push(Candidate(2, "Ito")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(3, "Tani")); CandidateList.push(Candidate(3, "Sato")); students[student4].Orvoted = true; //投票完了 address student5; //投票者5人目 GiveRight(student5); //投票権を受け取る //1回目の投票 students[student5].VoteName = "Nakamura"; require(ValidCandidate(student5)); //候補者リストにある名前かどうかチェック Remove("Nakamura"); //投票した候補者をリストから消す //2回目の投票 students[student5].VoteName = "Ito"; //上記の繰り返し require(ValidCandidate(student5)); Remove("Ito"); //3回目の投票 students[student5].VoteName = "Matsumoto"; require(ValidCandidate(student5)); Remove("Matsumoto"); CandidateList.push(Candidate(1, "Nakamura")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(3, "Ito")); CandidateList.push(Candidate(1, "Matsumoto")); students[student5].Orvoted = true; //投票完了 address student6; //投票者6人目 GiveRight(student6); //投票権を受け取る //1回目の投票 students[student6].VoteName = "Tanaka"; require(ValidCandidate(student6)); //候補者リストにある名前かどうかチェック Remove("Tanaka"); //投票した候補者をリストから消す //2回目の投票 students[student6].VoteName = "Sato"; //上記の繰り返し require(ValidCandidate(student6)); Remove("Sato"); //3回目の投票 students[student6].VoteName = "Matsumoto"; require(ValidCandidate(student6)); Remove("Matsumoto"); CandidateList.push(Candidate(1, "Tanaka")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(4, "Sato")); CandidateList.push(Candidate(2, "Matsumoto")); students[student6].Orvoted = true; //投票完了 address student7; //投票者7人目 GiveRight(student7); //投票権を受け取る //1回目の投票 students[student7].VoteName = "Ito"; require(ValidCandidate(student7)); //候補者リストにある名前かどうかチェック Remove("Ito"); //投票した候補者をリストから消す //2回目の投票 students[student7].VoteName = "Matsumoto"; //上記の繰り返し require(ValidCandidate(student7)); Remove("Matsumoto"); //3回目の投票 students[student7].VoteName = "Okamoto"; require(ValidCandidate(student7)); Remove("Okamoto"); CandidateList.push(Candidate(4, "Ito")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(3, "Matsumoto")); CandidateList.push(Candidate(1, "Okamoto")); students[student7].Orvoted = true; //投票完了 address student8; //投票者8人目 GiveRight(student8); //投票権を受け取る //1回目の投票 students[student8].VoteName = "Ito"; require(ValidCandidate(student8)); //候補者リストにある名前かどうかチェック Remove("Ito"); //投票した候補者をリストから消す //2回目の投票 students[student8].VoteName = "Tanaka"; //上記の繰り返し require(ValidCandidate(student8)); Remove("Tanaka"); //3回目の投票 students[student8].VoteName = "Okamoto"; require(ValidCandidate(student8)); Remove("Okamoto"); CandidateList.push(Candidate(5, "Ito")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(2, "Tanaka")); CandidateList.push(Candidate(2, "Okamoto")); students[student8].Orvoted = true; //投票完了 address student9; //投票者9人目 GiveRight(student9); //投票権を受け取る //1回目の投票 students[student9].VoteName = "Yamashita"; require(ValidCandidate(student9)); //候補者リストにある名前かどうかチェック Remove("Yamashita"); //投票した候補者をリストから消す //2回目の投票 students[student9].VoteName = "Sato"; //上記の繰り返し require(ValidCandidate(student9)); Remove("Sato"); //3回目の投票 students[student9].VoteName = "Tani"; require(ValidCandidate(student9)); Remove("Tani"); CandidateList.push(Candidate(3, "Yamashita")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(5, "Sato")); CandidateList.push(Candidate(4, "Tani")); students[student9].Orvoted = true; //投票完了 address student10; //投票者10人目 GiveRight(student10); //投票権を受け取る //1回目の投票 students[student10].VoteName = "Yamashita"; require(ValidCandidate(student10)); //候補者リストにある名前かどうかチェック Remove("Yamashita"); //投票した候補者をリストから消す //2回目の投票 students[student10].VoteName = "Kato"; //上記の繰り返し require(ValidCandidate(student10)); Remove("Kato"); //3回目の投票 students[student10].VoteName = "Ito"; require(ValidCandidate(student10)); Remove("Ito"); CandidateList.push(Candidate(4, "Yamashita")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(1, "Kato")); CandidateList.push(Candidate(6, "Ito")); students[student10].Orvoted = true; //投票完了 address student11; //投票者11人目 GiveRight(student11); //投票権を受け取る //1回目の投票 students[student11].VoteName = "Takahashi"; require(ValidCandidate(student11)); //候補者リストにある名前かどうかチェック Remove("Takahashi"); //投票した候補者をリストから消す //2回目の投票 students[student11].VoteName = "Kato"; //上記の繰り返し require(ValidCandidate(student11)); Remove("Kato"); //3回目の投票 students[student11].VoteName = "Nakamura"; require(ValidCandidate(student11)); Remove("Nakamura"); CandidateList.push(Candidate(3, "Takahashi")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(2, "Kato")); CandidateList.push(Candidate(2, "Nakamura")); students[student11].Orvoted = true; //投票完了 address student12; //投票者12人目 GiveRight(student12); //投票権を受け取る //1回目の投票 students[student12].VoteName = "Sato"; require(ValidCandidate(student12)); //候補者リストにある名前かどうかチェック Remove("Sato"); //投票した候補者をリストから消す //2回目の投票 students[student12].VoteName = "Okamoto"; //上記の繰り返し require(ValidCandidate(student12)); Remove("Okamoto"); //3回目の投票 students[student12].VoteName = "Tani"; require(ValidCandidate(student12)); Remove("Tani"); CandidateList.push(Candidate(6, "Sato")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(3, "Okamoto")); CandidateList.push(Candidate(5, "Tani")); students[student12].Orvoted = true; //投票完了 address student13; //投票者13人目 GiveRight(student13); //投票権を受け取る //1回目の投票 students[student13].VoteName = "Tanaka"; require(ValidCandidate(student13)); //候補者リストにある名前かどうかチェック Remove("Tanaka"); //投票した候補者をリストから消す //2回目の投票 students[student13].VoteName = "Kato"; //上記の繰り返し require(ValidCandidate(student13)); Remove("Kato"); //3回目の投票 students[student13].VoteName = "Matsumoto"; require(ValidCandidate(student13)); Remove("Matsumoto"); CandidateList.push(Candidate(3, "Tanaka")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(3, "Kato")); CandidateList.push(Candidate(4, "Matsumoto")); students[student13].Orvoted = true; //投票完了 address student14; //投票者14人目 GiveRight(student14); //投票権を受け取る //1回目の投票 students[student14].VoteName = "Nakamura"; require(ValidCandidate(student14)); //候補者リストにある名前かどうかチェック Remove("Nakamura"); //投票した候補者をリストから消す //2回目の投票 students[student14].VoteName = "Ito"; //上記の繰り返し require(ValidCandidate(student14)); Remove("Ito"); //3回目の投票 students[student14].VoteName = "Takahashi"; require(ValidCandidate(student14)); Remove("Takahashi"); CandidateList.push(Candidate(3, "Nakamura")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(7, "Ito")); CandidateList.push(Candidate(5, "Takahashi")); students[student14].Orvoted = true; //投票完了 address student15; //投票者15人目 GiveRight(student15); //投票権を受け取る //1回目の投票 students[student15].VoteName = "Tanaka"; require(ValidCandidate(student15)); //候補者リストにある名前かどうかチェック Remove("Tanaka"); //投票した候補者をリストから消す //2回目の投票 students[student15].VoteName = "Sato"; //上記の繰り返し require(ValidCandidate(student15)); Remove("Sato"); //3回目の投票 students[student15].VoteName = "Matsumoto"; require(ValidCandidate(student15)); Remove("Matsumoto"); CandidateList.push(Candidate(4, "Tanaka")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(7, "Sato")); CandidateList.push(Candidate(5, "Matsumoto")); students[student15].Orvoted = true; //投票完了 address student16; //投票者16人目 GiveRight(student16); //投票権を受け取る //1回目の投票 students[student16].VoteName = "Nakamura"; require(ValidCandidate(student16)); //候補者リストにある名前かどうかチェック Remove("Nakamura"); //投票した候補者をリストから消す //2回目の投票 students[student16].VoteName = "Kato"; //上記の繰り返し require(ValidCandidate(student16)); Remove("Kato"); //3回目の投票 students[student16].VoteName = "Yamashita"; require(ValidCandidate(student16)); Remove("Yamashita"); CandidateList.push(Candidate(4, "Nakamura")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(4, "Kato")); CandidateList.push(Candidate(5, "Yamashita")); students[student16].Orvoted = true; //投票完了 address student17; //投票者17人目 GiveRight(student17); //投票権を受け取る //1回目の投票 students[student17].VoteName = "Okamoto"; require(ValidCandidate(student17)); //候補者リストにある名前かどうかチェック Remove("Okamoto"); //投票した候補者をリストから消す //2回目の投票 students[student17].VoteName = "Ito"; //上記の繰り返し require(ValidCandidate(student17)); Remove("Ito"); //3回目の投票 students[student17].VoteName = "Tanaka"; require(ValidCandidate(student17)); Remove("Tanaka"); CandidateList.push(Candidate(4, "Okamoto")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(8, "Ito")); CandidateList.push(Candidate(5, "Tanaka")); students[student17].Orvoted = true; //投票完了 address student18; //投票者18人目 GiveRight(student18); //投票権を受け取る //1回目の投票 students[student18].VoteName = "Yamashita"; require(ValidCandidate(student18)); //候補者リストにある名前かどうかチェック Remove("Yamashita"); //投票した候補者をリストから消す //2回目の投票 students[student18].VoteName = "Ito"; //上記の繰り返し require(ValidCandidate(student18)); Remove("Ito"); //3回目の投票 students[student18].VoteName = "Takahashi"; require(ValidCandidate(student18)); Remove("Takahashi"); CandidateList.push(Candidate(6, "Yamashita")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(9, "Ito")); CandidateList.push(Candidate(6, "Takahashi")); students[student18].Orvoted = true; //投票完了 address student19; //投票者19人目 GiveRight(student19); //投票権を受け取る //1回目の投票 students[student19].VoteName = "Sato"; require(ValidCandidate(student19)); //候補者リストにある名前かどうかチェック Remove("Sato"); //投票した候補者をリストから消す //2回目の投票 students[student19].VoteName = "Tani"; //上記の繰り返し require(ValidCandidate(student19)); Remove("Tani"); //3回目の投票 students[student19].VoteName = "Nakamura"; require(ValidCandidate(student19)); Remove("Nakamura"); CandidateList.push(Candidate(8, "Sato")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(6, "Tani")); CandidateList.push(Candidate(5, "Nakamura")); students[student19].Orvoted = true; //投票完了 address student20; //投票者20人目 GiveRight(student20); //投票権を受け取る //1回目の投票 students[student20].VoteName = "Ito"; require(ValidCandidate(student20)); //候補者リストにある名前かどうかチェック Remove("Ito"); //投票した候補者をリストから消す //2回目の投票 students[student20].VoteName = "Nakamura"; //上記の繰り返し require(ValidCandidate(student20)); Remove("Nakamura"); //3回目の投票 students[student20].VoteName = "Kato"; require(ValidCandidate(student20)); Remove("Kato"); CandidateList.push(Candidate(10, "Ito")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(6, "Nakamura")); CandidateList.push(Candidate(5, "Kato")); students[student20].Orvoted = true; //投票完了 address student21; //投票者21人目 GiveRight(student21); //投票権を受け取る //1回目の投票 students[student21].VoteName = "Ito"; require(ValidCandidate(student21)); //候補者リストにある名前かどうかチェック Remove("Ito"); //投票した候補者をリストから消す //2回目の投票 students[student21].VoteName = "Matsumoto"; //上記の繰り返し require(ValidCandidate(student21)); Remove("Matsumoto"); //3回目の投票 students[student21].VoteName = "Okamoto"; require(ValidCandidate(student21)); Remove("Okamoto"); CandidateList.push(Candidate(11, "Ito")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(6, "Matsumoto")); CandidateList.push(Candidate(5, "Okamoto")); students[student21].Orvoted = true; //投票完了 address student22; //投票者22人目 GiveRight(student22); //投票権を受け取る //1回目の投票 students[student22].VoteName = "Tani"; require(ValidCandidate(student22)); //候補者リストにある名前かどうかチェック Remove("Tani"); //投票した候補者をリストから消す //2回目の投票 students[student22].VoteName = "Tanaka"; //上記の繰り返し require(ValidCandidate(student22)); Remove("Tanaka"); //3回目の投票 students[student22].VoteName = "Yamashita"; require(ValidCandidate(student22)); Remove("Yamashita"); CandidateList.push(Candidate(7, "Tani")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(6, "Tanaka")); CandidateList.push(Candidate(7, "Yamashita")); students[student22].Orvoted = true; //投票完了 address student23; //投票者23人目 GiveRight(student23); //投票権を受け取る //1回目の投票 students[student23].VoteName = "Okamoto"; require(ValidCandidate(student23)); //候補者リストにある名前かどうかチェック Remove("Okamoto"); //投票した候補者をリストから消す //2回目の投票 students[student23].VoteName = "Kato"; //上記の繰り返し require(ValidCandidate(student23)); Remove("Kato"); //3回目の投票 students[student23].VoteName = "Takahashi"; require(ValidCandidate(student23)); Remove("Takahashi"); CandidateList.push(Candidate(6, "Okamoto")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(6, "Kato")); CandidateList.push(Candidate(7, "Takahashi")); students[student23].Orvoted = true; //投票完了 address student24; //投票者24人目 GiveRight(student24); //投票権を受け取る //1回目の投票 students[student24].VoteName = "Tani"; require(ValidCandidate(student24)); //候補者リストにある名前かどうかチェック Remove("Tani"); //投票した候補者をリストから消す //2回目の投票 students[student24].VoteName = "Sato"; //上記の繰り返し require(ValidCandidate(student24)); Remove("Sato"); //3回目の投票 students[student24].VoteName = "Matsumoto"; require(ValidCandidate(student24)); Remove("Matsumoto"); CandidateList.push(Candidate(8, "Tani")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(9, "Sato")); CandidateList.push(Candidate(7, "Matsumoto")); students[student24].Orvoted = true; //投票完了 address student25; //投票者25人目 GiveRight(student25); //投票権を受け取る //1回目の投票 students[student25].VoteName = "Ito"; require(ValidCandidate(student25)); //候補者リストにある名前かどうかチェック Remove("Ito"); //投票した候補者をリストから消す //2回目の投票 students[student25].VoteName = "Sato"; //上記の繰り返し require(ValidCandidate(student25)); Remove("Sato"); //3回目の投票 students[student25].VoteName = "Nakamura"; require(ValidCandidate(student25)); Remove("Nakamura"); CandidateList.push(Candidate(12, "Ito")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(10, "Sato")); CandidateList.push(Candidate(7, "Nakamura")); students[student25].Orvoted = true; //投票完了 address student26; //投票者26人目 GiveRight(student26); //投票権を受け取る //1回目の投票 students[student26].VoteName = "Tani"; require(ValidCandidate(student26)); //候補者リストにある名前かどうかチェック Remove("Tani"); //投票した候補者をリストから消す //2回目の投票 students[student26].VoteName = "Yamashita"; //上記の繰り返し require(ValidCandidate(student26)); Remove("Yamashita"); //3回目の投票 students[student26].VoteName = "Kato"; require(ValidCandidate(student26)); Remove("Kato"); CandidateList.push(Candidate(9, "Tani")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(8, "Yamashita")); CandidateList.push(Candidate(7, "Kato")); students[student26].Orvoted = true; //投票完了 address student27; //投票者27人目 GiveRight(student27); //投票権を受け取る //1回目の投票 students[student27].VoteName = "Tani"; require(ValidCandidate(student27)); //候補者リストにある名前かどうかチェック Remove("Tani"); //投票した候補者をリストから消す //2回目の投票 students[student27].VoteName = "Ito"; //上記の繰り返し require(ValidCandidate(student27)); Remove("Ito"); //3回目の投票 students[student27].VoteName = "Okamoto"; require(ValidCandidate(student27)); Remove("Okamoto"); CandidateList.push(Candidate(10, "Tani")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(13, "Ito")); CandidateList.push(Candidate(7, "Okamoto")); students[student27].Orvoted = true; //投票完了 address student28; //投票者28人目 GiveRight(student28); //投票権を受け取る //1回目の投票 students[student28].VoteName = "Sato"; require(ValidCandidate(student28)); //候補者リストにある名前かどうかチェック Remove("Sato"); //投票した候補者をリストから消す //2回目の投票 students[student28].VoteName = "Matsumoto"; //上記の繰り返し require(ValidCandidate(student28)); Remove("Matsumoto"); //3回目の投票 students[student28].VoteName = "Tanaka"; require(ValidCandidate(student28)); Remove("Tanaka"); CandidateList.push(Candidate(11, "Sato")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(8, "Matsumoto")); CandidateList.push(Candidate(7, "Tanaka")); students[student28].Orvoted = true; //投票完了 address student29; //投票者29人目 GiveRight(student29); //投票権を受け取る //1回目の投票 students[student29].VoteName = "Ito"; require(ValidCandidate(student29)); //候補者リストにある名前かどうかチェック Remove("Ito"); //投票した候補者をリストから消す //2回目の投票 students[student29].VoteName = "Kato"; //上記の繰り返し require(ValidCandidate(student29)); Remove("Kato"); //3回目の投票 students[student29].VoteName = "Takahashi"; require(ValidCandidate(student29)); Remove("Takahashi"); CandidateList.push(Candidate(14, "Ito")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(8, "Kato")); CandidateList.push(Candidate(9, "Takahashi")); students[student29].Orvoted = true; //投票完了 address student30; //投票者30人目 GiveRight(student30); //投票権を受け取る //1回目の投票 students[student30].VoteName = "Sato"; require(ValidCandidate(student30)); //候補者リストにある名前かどうかチェック Remove("Sato"); //投票した候補者をリストから消す //2回目の投票 students[student30].VoteName = "Nakamura"; //上記の繰り返し require(ValidCandidate(student30)); Remove("Nakamura"); //3回目の投票 students[student30].VoteName = "Yamashita"; require(ValidCandidate(student30)); Remove("Yamashita"); CandidateList.push(Candidate(12, "Sato")); //投票先の候補者の得票数を増やしてリストに追加する CandidateList.push(Candidate(8, "Nakamura")); CandidateList.push(Candidate(9, "Yamashita")); students[student30].Orvoted = true; //投票完了 sort(CandidateList); //得票数の結果を昇順に並び替える } //投票した候補者を一時的にリストから取り除く function Remove(string memory name) public { for(uint p = 0; p < CandidateList.length; p++) { if(keccak256(abi.encodePacked(CandidateList[p].Name)) == keccak256(abi.encodePacked(name))) { delete CandidateList[p]; } } } //投票先の名前と候補者名が一致しているかどうか function ValidCandidate(address student) view public returns (bool) { //投票者が書いた名前がCandidateListの中に存在するか比較して判定する for(uint i = 0; i < CandidateList.length; i++) { if (keccak256(abi.encodePacked(CandidateList[i].Name)) == keccak256(abi.encodePacked(students[student].VoteName))) { return true; } } return false; } //クイックソートの呼び出し function sort(Candidate[] memory) public returns (Candidate[] memory) { quickSort(CandidateList, 0, CandidateList.length - 1); return CandidateList; } //集計結果を昇順に並び替え(クイックソート) function quickSort(Candidate[] memory sub, uint left, uint right) internal { uint s = left; uint t = right; if (s < t) { uint pivot = sub[uint((left + right) / 2)].VotesReceived; while(s <= t) { while (sub[uint(s)].VotesReceived < pivot) { s++; } while (pivot < sub[uint(t)].VotesReceived) { t--; } if (s <= t) { (sub[uint(s)].VotesReceived, sub[uint(t)].VotesReceived) = (sub[uint(t)].VotesReceived, sub[uint(s)].VotesReceived); s++; t--; } } if (left < t) { quickSort(sub, left, t); } if (s < right) { quickSort(sub, s, right); } } } }
投票先の候補者の得票数を増やしてリストに追加する
CandidateList.push(Candidate(7, "Tani"));
12,713,897
[ 1, 167, 237, 248, 168, 103, 106, 166, 232, 235, 164, 228, 111, 166, 227, 252, 169, 101, 255, 169, 227, 232, 164, 228, 111, 166, 127, 250, 168, 103, 106, 167, 248, 113, 164, 229, 245, 166, 100, 250, 164, 229, 231, 164, 228, 250, 164, 228, 104, 164, 230, 108, 164, 229, 122, 164, 230, 235, 164, 228, 109, 169, 128, 126, 166, 237, 259, 164, 228, 252, 164, 229, 238, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 385, 8824, 682, 18, 6206, 12, 11910, 12, 27, 16, 315, 56, 28662, 7923, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]