file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./partial_match/1/0xC62b8c58984a7f9E15933bC9E20159D240Ab0D8D/sources/contracts/protocol/tokenization/base/MintableIncentivizedERC721.sol
See {IERC721-safeTransferFrom}./
function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) external virtual override nonReentrant { _safeTransferFrom(from, to, tokenId, _data); }
2,783,966
/** *Submitted for verification at Etherscan.io on 2022-01-21 */ pragma solidity ^0.5.16; contract ESG { /// @notice EIP-20 token name for this token string public constant name = "ESG"; /// @notice EIP-20 token symbol for this token string public constant symbol = "ESG"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public constant totalSupply = 49000000e18; // 49 million ESG in Ethereum /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new ESG token * @param account The initial account to grant all the tokens */ constructor (address account) public{ balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)) { amount = uint96(0xffffffffffffffffffffffff); } else { amount = safe96(rawAmount, "ESG::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "ESG::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "ESG::transferFrom: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(0xffffffffffffffffffffffff)) { uint96 newAllowance = sub96(spenderAllowance, amount, "ESG::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "ESG::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "ESG::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "ESG::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint96) { require(blockNumber < block.number, "ESG::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "ESG::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "ESG::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "ESG::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "ESG::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "ESG::_moveDelegates: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "ESG::_moveDelegates: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "ESG::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
Transfer `amount` tokens from `src` to `dst` src The address of the source account dst The address of the destination account rawAmount The number of tokens to transfer return Whether or not the transfer succeeded/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "ESG::transferFrom: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(0xffffffffffffffffffffffff)) { uint96 newAllowance = sub96(spenderAllowance, amount, "ESG::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; }
15,082,049
./full_match/4/0x139651987B3a38B4a9adb60Ad81209f601721Cc8/sources/contracts/FundMe.sol
uint256 minimumUSD = 1 10 18;require(getConvertionRate(msg.value) >= minimumUSD, "you need to spend more ETH!");
function fund() public payable{ addressToAmountFunded[msg.sender] += msg.value; }
13,358,351
./partial_match/1/0xcfDE5CF330a76fa69DFeb9B0f5feBa2dF803B7D3/sources/PPPP01PP.sol
exclude from paying fees
constructor() ERC20("PeppaPaulyPotterPunk01PP", "POLYGON") { uint256 _buyMarketingFee = 15; uint256 _buyLiquidityFee = 0; uint256 _sellMarketingFee = 40; uint256 _sellLiquidityFee = 0; uint256 totalSupply = 100000000 * 1e9; maxTransactionAmount = (totalSupply) / 50; maxWallet = (totalSupply) / 50; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyTotalFees = buyMarketingFee + buyLiquidityFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellTotalFees = sellMarketingFee + sellLiquidityFee; _isExcludedFromFees[msg.sender] = true; _isExcludedFromFees[marketingWallet] = true; _isExcludedFromFees[address(this)] = true; _isExcludedFromFees[address(0xdead)] = true; _isExcludedMaxTransactionAmount[owner()] = true; _isExcludedMaxTransactionAmount[address(this)] = true; _isExcludedMaxTransactionAmount[address(0xdead)] = true; _isExcludedMaxTransactionAmount[marketingWallet] = true; _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
9,306,446
./full_match/5/0xeDeE35dA2492c30024BC6Ca5718B84c5fA8b9037/sources/project_/contracts/SweetToken.sol
Locks a certain amount of tokens for an account account address of the account to lock tokens for amount amount of tokens to lock/ Calculate the new total amount for the "whale" condition (considering only the amount of the current transaction)
function _lockTokens(address account, uint256 amount) internal { uint256 newPurchaseLocked = amount * LOCKED_TOKEN_PERCENTAGE / 100; uint256 previouslyLocked = _locked[account].amount; uint256 randomBlocksPerPeriod = blocksPerUnlockPeriodPool[uint256(keccak256(abi.encodePacked(block.timestamp, account, amount))) % blocksPerUnlockPeriodPool.length]; uint256 newBlocksPerPeriod; if (amount >= totalSupply() / 100 || _isWhale[account]) { newBlocksPerPeriod = WHALE_BLOCKS_PER_UNLOCK_PERIOD; } _locked[account].blocksPerPeriod = newBlocksPerPeriod; emit TokensLocked(account, newPurchaseLocked); }
1,859,923
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPeripheryPayments { /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH. /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users. /// @param amountMinimum The minimum amount of WETH9 to unwrap /// @param recipient The address receiving ETH function unwrapWETH9(uint256 amountMinimum, address recipient) external payable; /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() external payable; /// @notice Transfers the full amount of a token held by this contract to recipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users /// @param token The contract address of the token which will be transferred to `recipient` /// @param amountMinimum The minimum amount of token required for a transfer /// @param recipient The destination address of the token function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable; } /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback, IPeripheryPayments { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); }
Periphery Payments Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments { function unwrapWETH9(uint256 amountMinimum, address recipient) external payable; function refundETH() external payable; function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable; pragma solidity ^0.6.0; }
15,808,598
pragma solidity 0.5.17; import "@keep-network/sortition-pools/contracts/AbstractSortitionPool.sol"; contract CandidatesPools { // Notification that a new sortition pool has been created. event SortitionPoolCreated( address indexed application, address sortitionPool ); // Mapping of pools with registered member candidates for each application. mapping(address => address) candidatesPools; // application -> candidates pool /// @notice Creates new sortition pool for the application. /// @dev Emits an event after sortition pool creation. /// @param _application Address of the application. /// @return Address of the created sortition pool contract. function createSortitionPool(address _application) external returns (address) { require( candidatesPools[_application] == address(0), "Sortition pool already exists" ); address sortitionPoolAddress = newSortitionPool(_application); candidatesPools[_application] = sortitionPoolAddress; emit SortitionPoolCreated(_application, sortitionPoolAddress); return candidatesPools[_application]; } /// @notice Register caller as a candidate to be selected as keep member /// for the provided customer application. /// @dev If caller is already registered it returns without any changes. /// @param _application Address of the application. function registerMemberCandidate(address _application) external { AbstractSortitionPool candidatesPool = AbstractSortitionPool( getSortitionPool(_application) ); address operator = msg.sender; if (!candidatesPool.isOperatorInPool(operator)) { candidatesPool.joinPool(operator); } } /// @notice Checks if operator's details in the member candidates pool are /// up to date for the given application. If not update operator status /// function should be called by the one who is monitoring the status. /// @param _operator Operator's address. /// @param _application Customer application address. function isOperatorUpToDate(address _operator, address _application) external view returns (bool) { return getSortitionPoolForOperator(_operator, _application) .isOperatorUpToDate(_operator); } /// @notice Invokes update of operator's details in the member candidates pool /// for the given application /// @param _operator Operator's address. /// @param _application Customer application address. function updateOperatorStatus(address _operator, address _application) external { getSortitionPoolForOperator(_operator, _application) .updateOperatorStatus(_operator); } /// @notice Gets the sortition pool address for the given application. /// @dev Reverts if sortition does not exist for the application. /// @param _application Address of the application. /// @return Address of the sortition pool contract. function getSortitionPool(address _application) public view returns (address) { require( candidatesPools[_application] != address(0), "No pool found for the application" ); return candidatesPools[_application]; } /// @notice Checks if operator is registered as a candidate for the given /// customer application. /// @param _operator Operator's address. /// @param _application Customer application address. /// @return True if operator is already registered in the candidates pool, /// false otherwise. function isOperatorRegistered(address _operator, address _application) public view returns (bool) { if (candidatesPools[_application] == address(0)) { return false; } AbstractSortitionPool candidatesPool = AbstractSortitionPool( candidatesPools[_application] ); return candidatesPool.isOperatorRegistered(_operator); } /// @notice Checks if given operator is eligible for the given application. /// @param _operator Operator's address. /// @param _application Customer application address. function isOperatorEligible(address _operator, address _application) public view returns (bool) { if (candidatesPools[_application] == address(0)) { return false; } AbstractSortitionPool candidatesPool = AbstractSortitionPool( candidatesPools[_application] ); return candidatesPool.isOperatorEligible(_operator); } /// @notice Gets the total weight of operators /// in the sortition pool for the given application. /// @dev Reverts if sortition does not exits for the application. /// @param _application Address of the application. /// @return The sum of all registered operators' weights in the pool. /// Reverts if sortition pool for the application does not exist. function getSortitionPoolWeight(address _application) public view returns (uint256) { return AbstractSortitionPool(getSortitionPool(_application)).totalWeight(); } /// @notice Creates new sortition pool for the application. /// @dev Have to be implemented by keep factory to call desired sortition /// pool factory. /// @param _application Address of the application. /// @return Address of the created sortition pool contract. function newSortitionPool(address _application) internal returns (address); /// @notice Gets bonded sortition pool of specific application for the /// operator. /// @dev Reverts if the operator is not registered for the application. /// @param _operator Operator's address. /// @param _application Customer application address. /// @return Bonded sortition pool. function getSortitionPoolForOperator( address _operator, address _application ) internal view returns (AbstractSortitionPool) { require( isOperatorRegistered(_operator, _application), "Operator not registered for the application" ); return AbstractSortitionPool(candidatesPools[_application]); } }
Creates new sortition pool for the application. Have to be implemented by keep factory to call desired sortition pool factory. _application Address of the application. return Address of the created sortition pool contract. Gets bonded sortition pool of specific application for the operator. Reverts if the operator is not registered for the application. _operator Operator's address. _application Customer application address. return Bonded sortition pool.
function newSortitionPool(address _application) internal returns (address); function getSortitionPoolForOperator( address _operator, address _application ) internal view returns (AbstractSortitionPool) { require( isOperatorRegistered(_operator, _application), "Operator not registered for the application" ); return AbstractSortitionPool(candidatesPools[_application]); }
12,902,625
// SPDX-License-Identifier: MIT // // Copyright (c) 2021 Kentaro Hara // // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php pragma solidity ^0.8.11; import "../JohnLawCoin.sol"; //------------------------------------------------------------------------------ // [JohnLawCoin contract] // // JohnLawCoin is implemented as ERC20 tokens. // // Permission: Except public getters, only the ACB can call the methods. // Coin holders can transfer their coins using the ERC20 token APIs. //------------------------------------------------------------------------------ contract JohnLawCoin_v2 is ERC20PausableUpgradeable, OwnableUpgradeable { // Constants. // Name of the ERC20 token. string public constant NAME = "JohnLawCoin"; // Symbol of the ERC20 token. string public constant SYMBOL = "JLC"; // The initial coin supply. uint public constant INITIAL_COIN_SUPPLY = 10000000; // The tax rate. uint public constant TAX_RATE = 1; // Attributes. // The account to which the tax is sent. address public tax_account_; address public tax_account_v2_; mapping (address => uint) public dummy_; // Events. event TransferEvent(address indexed sender, address receiver, uint amount, uint tax); function upgrade() public onlyOwner { tax_account_v2_ = tax_account_; } // Mint coins to one account. // // Parameters // ---------------- // |account|: The account to which the coins are minted. // |amount|: The amount to be minted. // // Returns // ---------------- // None. function mint(address account, uint amount) public onlyOwner { mint_v2(account, amount); } function mint_v2(address account, uint amount) public onlyOwner { _mint(account, amount); dummy_[account] = amount; } // Burn coins from one account. // // Parameters // ---------------- // |account|: The account from which the coins are burned. // |amount|: The amount to be burned. // // Returns // ---------------- // None. function burn(address account, uint amount) public onlyOwner { burn_v2(account, amount); } function burn_v2(address account, uint amount) public onlyOwner { _burn(account, amount); dummy_[account] = amount; } // Move coins from one account to another account. Coin holders should use // ERC20's transfer method instead. // // Parameters // ---------------- // |sender|: The sender account. // |receiver|: The receiver account. // |amount|: The amount to be moved. // // Returns // ---------------- // None. function move(address sender, address receiver, uint amount) public onlyOwner { move_v2(sender, receiver, amount); } function move_v2(address sender, address receiver, uint amount) public onlyOwner { _transfer(sender, receiver, amount); dummy_[receiver] = amount; } // Pause the contract. function pause() public onlyOwner { if (!paused()) { _pause(); } } // Unpause the contract. function unpause() public onlyOwner { if (paused()) { _unpause(); } } // Override decimals. function decimals() public pure override returns (uint8) { return 18; } // Set the tax rate. function resetTaxAccount() public onlyOwner { resetTaxAccount_v2(); } function resetTaxAccount_v2() public onlyOwner { address old_tax_account = tax_account_v2_; tax_account_v2_ = address(uint160(uint(keccak256(abi.encode( "tax_v2", block.number))))); move(old_tax_account, tax_account_v2_, balanceOf(old_tax_account)); tax_account_v2_ = tax_account_; } // Override ERC20's transfer method to impose a tax set by the ACB. // // Parameters // ---------------- // |account|: The receiver account. // |amount|: The amount to be transferred. // // Returns // ---------------- // None. function transfer(address account, uint amount) public override returns (bool) { return transfer_v2(account, amount); } function transfer_v2(address account, uint amount) public returns (bool) { uint tax = amount * TAX_RATE / 100; _transfer(_msgSender(), tax_account_v2_, tax); _transfer(_msgSender(), account, amount - tax); emit TransferEvent(_msgSender(), account, amount - tax, tax); return true; } } //------------------------------------------------------------------------------ // [JohnLawBond contract] // // JohnLawBond is an implementation of the bonds to increase / decrease the // total coin supply. The bonds are not transferable. // // Permission: Except public getters, only the ACB can call the methods. //------------------------------------------------------------------------------ contract JohnLawBond_v2 is OwnableUpgradeable { using EnumerableSet for EnumerableSet.UintSet; // Attributes. // _bonds[account][redemption_epoch] stores the number of the bonds // owned by the |account| that become redeemable at |redemption_epoch|. mapping (address => mapping (uint => uint)) private _bonds; // _redemption_epochs[account] is a set of the redemption epochs of the // bonds owned by the |account|. mapping (address => EnumerableSet.UintSet) private _redemption_epochs; // _bond_count[account] is the number of the bonds owned by the |account|. mapping (address => uint) private _bond_count; // _bond_supply[redemption_epoch] is the total number of the bonds that // become redeemable at |redemption_epoch|. mapping (uint => uint) private _bond_supply; // The total bond supply. uint private _total_supply; uint private _total_supply_v2; mapping (address => mapping (uint => uint)) private _bonds_v2; mapping (address => EnumerableSet.UintSet) private _redemption_epochs_v2; mapping (address => uint) private _bond_count_v2; mapping (uint => uint) private _bond_supply_v2; // Events. event MintEvent(address indexed account, uint redemption_epoch, uint amount); event BurnEvent(address indexed account, uint redemption_epoch, uint amount); function upgrade() public onlyOwner { _total_supply_v2 = _total_supply; for (uint epoch = 0; epoch < 100; epoch++) { _bond_supply_v2[epoch] = _bond_supply[epoch]; } } // Mint bonds to one account. // // Parameters // ---------------- // |account|: The account to which the bonds are minted. // |redemption_epoch|: The redemption epoch of the bonds. // |amount|: The amount to be minted. // // Returns // ---------------- // None. function mint(address account, uint redemption_epoch, uint amount) public onlyOwner { mint_v2(account, redemption_epoch, amount); } function mint_v2(address account, uint redemption_epoch, uint amount) public onlyOwner { _bonds[account][redemption_epoch] += amount; _bonds_v2[account][redemption_epoch] += amount; _total_supply_v2 += amount; _bond_count[account] += amount; _bond_count_v2[account] += amount; _bond_supply[redemption_epoch] += amount; _bond_supply_v2[redemption_epoch] += amount; if (_bonds[account][redemption_epoch] > 0) { _redemption_epochs[account].add(redemption_epoch); _redemption_epochs_v2[account].add(redemption_epoch); } emit MintEvent(account, redemption_epoch, amount); } // Burn bonds from one account. // // Parameters // ---------------- // |account|: The account from which the bonds are burned. // |redemption_epoch|: The redemption epoch of the bonds. // |amount|: The amount to be burned. // // Returns // ---------------- // None. function burn(address account, uint redemption_epoch, uint amount) public onlyOwner { burn_v2(account, redemption_epoch, amount); } function burn_v2(address account, uint redemption_epoch, uint amount) public onlyOwner { _bonds[account][redemption_epoch] -= amount; _bonds_v2[account][redemption_epoch] += amount; _total_supply_v2 -= amount; _bond_count[account] -= amount; _bond_count_v2[account] += amount; // Use + to avoid underflow. _bond_supply[redemption_epoch] -= amount; _bond_supply_v2[redemption_epoch] -= amount; if (_bonds[account][redemption_epoch] == 0) { _redemption_epochs[account].remove(redemption_epoch); _redemption_epochs_v2[account].remove(redemption_epoch); } emit BurnEvent(account, redemption_epoch, amount); } // Public getter: Return the number of the bonds owned by the |account|. function numberOfBondsOwnedBy(address account) public view returns (uint) { return _bond_count[account]; } // Public getter: Return the number of redemption epochs of the bonds // owned by the |account|. function numberOfRedemptionEpochsOwnedBy(address account) public view returns (uint) { return _redemption_epochs[account].length(); } // Public getter: Return the |index|-th redemption epoch of the bonds // owned by the |account|. |index| must be smaller than the value returned by // numberOfRedemptionEpochsOwnedBy(account). function getRedemptionEpochOwnedBy(address account, uint index) public view returns (uint) { return _redemption_epochs[account].at(index); } // Public getter: Return the number of the bonds owned by the |account| that // become redeemable at |redemption_epoch|. function balanceOf(address account, uint redemption_epoch) public view returns (uint) { return balanceOf_v2(account, redemption_epoch); } function balanceOf_v2(address account, uint redemption_epoch) public view returns (uint) { return _bonds[account][redemption_epoch]; } // Public getter: Return the total bond supply. function totalSupply() public view returns (uint) { return _total_supply_v2; } // Public getter: Return the number of the bonds that become redeemable at // |redemption_epoch|. function bondSupplyAt(uint redemption_epoch) public view returns (uint) { return _bond_supply_v2[redemption_epoch]; } } //------------------------------------------------------------------------------ // [Oracle contract] // // The oracle is a decentralized mechanism to determine one "truth" level // from 0, 1, 2, ..., LEVEL_MAX - 1. The oracle uses the commit-reveal-reclaim // voting scheme. // // Permission: Except public getters, only the ACB can call the methods. //------------------------------------------------------------------------------ contract Oracle_v2 is OwnableUpgradeable { // Constants. The values are defined in initialize(). The values never change // during the contract execution but use 'public' (instead of 'constant') // because tests want to override the values. uint public LEVEL_MAX; uint public RECLAIM_THRESHOLD; uint public PROPORTIONAL_REWARD_RATE; // The valid phase transition is: COMMIT => REVEAL => RECLAIM. enum Phase { COMMIT, REVEAL, RECLAIM } // Commit is a struct to manage one commit entry in the commit-reveal-reclaim // scheme. struct Commit { // The committed hash (filled in the commit phase). bytes32 hash; // The amount of deposited coins (filled in the commit phase). uint deposit; // The oracle level (filled in the reveal phase). uint oracle_level; // The phase of this commit entry. Phase phase; // The epoch ID when this commit entry is created. uint epoch_id; bytes32 hash_v2; uint deposit_v2; uint oracle_level_v2; uint epoch_id_v2; } // Vote is a struct to aggregate voting statistics for each oracle level. // The data is aggregated during the reveal phase and finalized at the end // of the reveal phase. struct Vote { // The total amount of the coins deposited by the voters who voted for this // oracle level. uint deposit; // The number of the voters. uint count; // Set to true when the voters for this oracle level are eligible to // reclaim the coins they deposited. bool should_reclaim; // Set to true when the voters for this oracle level are eligible to // receive a reward. bool should_reward; bool should_reclaim_v2; bool should_reward_v2; uint deposit_v2; uint count_v2; } // Epoch is a struct to keep track of the states in the commit-reveal-reclaim // scheme. The oracle creates three Epoch objects and uses them in a // round-robin manner. For example, when the first Epoch object is in use for // the commit phase, the second Epoch object is in use for the reveal phase, // and the third Epoch object is in use for the reclaim phase. struct Epoch { // The commit entries. mapping (address => Commit) commits; // The voting statistics for all the oracle levels. This uses a mapping // (instead of an array) to make the Vote struct upgradeable. mapping (uint => Vote) votes; // An account to store coins deposited by the voters. address deposit_account; // An account to store the reward. address reward_account; // The total amount of the reward. uint reward_total; // The current phase of this Epoch. Phase phase; address deposit_account_v2; address reward_account_v2; uint reward_total_v2; Phase phase_v2; } // Attributes. See the comment in initialize(). // This uses a mapping (instead of an array) to make the Epoch struct // upgradeable. mapping (uint => Epoch) public epochs_; uint public epoch_id_; uint public epoch_id_v2_; // Events. event CommitEvent(address indexed sender, uint indexed epoch_id, bytes32 hash, uint deposited); event RevealEvent(address indexed sender, uint indexed epoch_id, uint oracle_level, uint salt); event ReclaimEvent(address indexed sender, uint indexed epoch_id, uint deposited, uint rewarded); event AdvancePhaseEvent(uint indexed epoch_id, uint tax, uint burned); function upgrade() public onlyOwner { epoch_id_v2_ = epoch_id_; for (uint epoch_index = 0; epoch_index < 3; epoch_index++) { epochs_[epoch_index].deposit_account_v2 = epochs_[epoch_index].deposit_account; epochs_[epoch_index].reward_account_v2 = epochs_[epoch_index].reward_account; epochs_[epoch_index].reward_total_v2 = epochs_[epoch_index].reward_total; epochs_[epoch_index].phase_v2 = epochs_[epoch_index].phase; for (uint level = 0; level < LEVEL_MAX; level++) { Vote storage vote = epochs_[epoch_index].votes[level]; vote.should_reclaim_v2 = vote.should_reclaim; vote.should_reward_v2 = vote.should_reward; vote.deposit_v2 = vote.deposit; vote.count_v2 = vote.count; } } } // Do commit. // // Parameters // ---------------- // |sender|: The voter's account. // |hash|: The committed hash. // |deposit|: The amount of the deposited coins. // |coin|: The JohnLawCoin contract. The ownership needs to be transferred to // this contract. // // Returns // ---------------- // True if the commit succeeded. False otherwise. function commit(address sender, bytes32 hash, uint deposit, JohnLawCoin_v2 coin) public onlyOwner returns (bool) { return commit_v2(sender, hash, deposit, coin); } function commit_v2(address sender, bytes32 hash, uint deposit, JohnLawCoin_v2 coin) public onlyOwner returns (bool) { Epoch storage epoch = epochs_[epoch_id_v2_ % 3]; require(epoch.phase_v2 == Phase.COMMIT, "co1"); if (coin.balanceOf(sender) < deposit) { return false; } // One voter can commit only once per phase. if (epoch.commits[sender].epoch_id == epoch_id_v2_) { return false; } // Create a commit entry. epoch.commits[sender] = Commit( hash, deposit, LEVEL_MAX, Phase.COMMIT, epoch_id_v2_, hash, deposit, LEVEL_MAX, epoch_id_v2_); require(epoch.commits[sender].phase == Phase.COMMIT, "co2"); // Move the deposited coins to the deposit account. coin.move(sender, epoch.deposit_account_v2, deposit); emit CommitEvent(sender, epoch_id_v2_, hash, deposit); return true; } // Do reveal. // // Parameters // ---------------- // |sender|: The voter's account. // |oracle_level|: The oracle level revealed by the voter. // |salt|: The salt revealed by the voter. // // Returns // ---------------- // True if the reveal succeeded. False otherwise. function reveal(address sender, uint oracle_level, uint salt) public onlyOwner returns (bool) { return reveal_v2(sender, oracle_level, salt); } function reveal_v2(address sender, uint oracle_level, uint salt) public onlyOwner returns (bool) { Epoch storage epoch = epochs_[(epoch_id_v2_ - 1) % 3]; require(epoch.phase_v2 == Phase.REVEAL, "rv1"); if (LEVEL_MAX <= oracle_level) { return false; } if (epoch.commits[sender].epoch_id != epoch_id_v2_ - 1) { // The corresponding commit was not found. return false; } // One voter can reveal only once per phase. if (epoch.commits[sender].phase != Phase.COMMIT) { return false; } epoch.commits[sender].phase = Phase.REVEAL; // Check if the committed hash matches the revealed level and the salt. bytes32 reveal_hash = encrypt( sender, oracle_level, salt); bytes32 hash = epoch.commits[sender].hash; if (hash != reveal_hash) { return false; } // Update the commit entry with the revealed level. epoch.commits[sender].oracle_level = oracle_level; // Count up the vote. epoch.votes[oracle_level].deposit_v2 += epoch.commits[sender].deposit; epoch.votes[oracle_level].count_v2 += 1; emit RevealEvent(sender, epoch_id_v2_, oracle_level, salt); return true; } // Do reclaim. // // Parameters // ---------------- // |sender|: The voter's account. // |coin|: The JohnLawCoin contract. The ownership needs to be transferred to // this contract. // // Returns // ---------------- // A tuple of two values: // - uint: The amount of the reclaimed coins. This becomes a positive value // when the voter is eligible to reclaim their deposited coins. // - uint: The amount of the reward. This becomes a positive value when the // voter voted for the "truth" oracle level. function reclaim(address sender, JohnLawCoin_v2 coin) public onlyOwner returns (uint, uint) { return reclaim_v2(sender, coin); } function reclaim_v2(address sender, JohnLawCoin_v2 coin) public onlyOwner returns (uint, uint) { Epoch storage epoch = epochs_[(epoch_id_v2_ - 2) % 3]; require(epoch.phase_v2 == Phase.RECLAIM, "rc1"); if (epoch.commits[sender].epoch_id != epoch_id_v2_ - 2){ // The corresponding commit was not found. return (0, 0); } // One voter can reclaim only once per phase. if (epoch.commits[sender].phase != Phase.REVEAL) { return (0, 0); } epoch.commits[sender].phase = Phase.RECLAIM; uint deposit = epoch.commits[sender].deposit; uint oracle_level = epoch.commits[sender].oracle_level; if (oracle_level == LEVEL_MAX) { return (0, 0); } require(0 <= oracle_level && oracle_level < LEVEL_MAX, "rc2"); if (!epoch.votes[oracle_level].should_reclaim_v2) { return (0, 0); } require(epoch.votes[oracle_level].count_v2 > 0, "rc3"); // Reclaim the deposited coins. coin.move(epoch.deposit_account_v2, sender, deposit); uint reward = 0; if (epoch.votes[oracle_level].should_reward_v2) { // The voter who voted for the "truth" level can receive the reward. // // The PROPORTIONAL_REWARD_RATE of the reward is distributed to the // voters in proportion to the coins they deposited. This incentivizes // voters who have more coins (and thus have more power on determining // the "truth" level) to join the oracle. // // The rest of the reward is distributed to the voters evenly. This // incentivizes more voters (including new voters) to join the oracle. if (epoch.votes[oracle_level].deposit_v2 > 0) { reward += (uint(PROPORTIONAL_REWARD_RATE) * epoch.reward_total_v2 * deposit) / (uint(100) * epoch.votes[oracle_level].deposit_v2); } reward += ((uint(100) - PROPORTIONAL_REWARD_RATE) * epoch.reward_total_v2) / (uint(100) * epoch.votes[oracle_level].count_v2); coin.move(epoch.reward_account_v2, sender, reward); } emit ReclaimEvent(sender, epoch_id_v2_, deposit, reward); return (deposit, reward); } // Advance to the next phase. COMMIT => REVEAL, REVEAL => RECLAIM, // RECLAIM => COMMIT. // // Parameters // ---------------- // |coin|: The JohnLawCoin contract. The ownership needs to be transferred to // this contract. // // Returns // ---------------- // None. function advance(JohnLawCoin_v2 coin) public onlyOwner returns (uint) { return advance_v2(coin); } function advance_v2(JohnLawCoin_v2 coin) public onlyOwner returns (uint) { // Advance the phase. epoch_id_v2_ += 1; epoch_id_ += 1; // Step 1: Move the commit phase to the reveal phase. Epoch storage epoch = epochs_[(epoch_id_v2_ - 1) % 3]; require(epoch.phase_v2 == Phase.COMMIT, "ad1"); epoch.phase_v2 = Phase.REVEAL; // Step 2: Move the reveal phase to the reclaim phase. epoch = epochs_[(epoch_id_v2_ - 2) % 3]; require(epoch.phase_v2 == Phase.REVEAL, "ad2"); epoch.phase_v2 = Phase.RECLAIM; // The "truth" level is set to the mode of the weighted majority votes. uint mode_level = getModeLevel(); if (0 <= mode_level && mode_level < LEVEL_MAX) { uint deposit_revealed = 0; uint deposit_to_reclaim = 0; for (uint level = 0; level < LEVEL_MAX; level++) { require(epoch.votes[level].should_reclaim_v2 == false, "ad3"); require(epoch.votes[level].should_reward_v2 == false, "ad4"); deposit_revealed += epoch.votes[level].deposit_v2; if ((mode_level < RECLAIM_THRESHOLD || mode_level - RECLAIM_THRESHOLD <= level) && level <= mode_level + RECLAIM_THRESHOLD) { // Voters who voted for the oracle levels in [mode_level - // reclaim_threshold, mode_level + reclaim_threshold] are eligible // to reclaim their deposited coins. Other voters lose their deposited // coins. epoch.votes[level].should_reclaim_v2 = true; deposit_to_reclaim += epoch.votes[level].deposit_v2; } } // Voters who voted for the "truth" level are eligible to receive the // reward. epoch.votes[mode_level].should_reward_v2 = true; // Note: |deposit_revealed| is equal to // |balanceOf(epoch.deposit_account_v2)| // only when all the voters who voted in the commit phase revealed // their votes correctly in the reveal phase. require(deposit_revealed <= coin.balanceOf(epoch.deposit_account_v2), "ad5"); require(deposit_to_reclaim <= coin.balanceOf(epoch.deposit_account_v2), "ad6"); // The lost coins are moved to the reward account. coin.move( epoch.deposit_account_v2, epoch.reward_account_v2, coin.balanceOf(epoch.deposit_account_v2) - deposit_to_reclaim); } // Move the collected tax to the reward account. address tax_account = coin.tax_account_v2_(); uint tax = coin.balanceOf(tax_account); coin.move(tax_account, epoch.reward_account_v2, tax); // Set the total amount of the reward. epoch.reward_total_v2 = coin.balanceOf(epoch.reward_account_v2); // Step 3: Move the reclaim phase to the commit phase. uint epoch_index = epoch_id_v2_ % 3; epoch = epochs_[epoch_index]; require(epoch.phase_v2 == Phase.RECLAIM, "ad7"); uint burned = coin.balanceOf(epoch.deposit_account_v2) + coin.balanceOf(epoch.reward_account_v2); // Burn the remaining deposited coins. coin.burn(epoch.deposit_account_v2, coin.balanceOf( epoch.deposit_account_v2)); // Burn the remaining reward. coin.burn(epoch.reward_account_v2, coin.balanceOf(epoch.reward_account_v2)); // Initialize the Epoch object for the next commit phase. // // |epoch.commits_| cannot be cleared due to the restriction of Solidity. // |epoch_id_| ensures the stale commit entries are not misused. for (uint level = 0; level < LEVEL_MAX; level++) { epoch.votes[level] = Vote(0, 0, false, false, false, false, 0, 0); } // Regenerate the account addresses just in case. require(coin.balanceOf(epoch.deposit_account_v2) == 0, "ad8"); require(coin.balanceOf(epoch.reward_account_v2) == 0, "ad9"); epoch.deposit_account_v2 = address(uint160(uint(keccak256(abi.encode( "deposit_v2", epoch_index, block.number))))); epoch.reward_account_v2 = address(uint160(uint(keccak256(abi.encode( "reward_v2", epoch_index, block.number))))); epoch.reward_total_v2 = 0; epoch.phase_v2 = Phase.COMMIT; emit AdvancePhaseEvent(epoch_id_v2_, tax, burned); return burned; } // Return the oracle level that got the largest amount of deposited coins. // In other words, return the mode of the votes weighted by the deposited // coins. // // Parameters // ---------------- // None. // // Returns // ---------------- // If there are multiple modes, return the mode that has the largest votes. // If there are multiple modes that have the largest votes, return the // smallest mode. If there are no votes, return LEVEL_MAX. function getModeLevel() public onlyOwner view returns (uint) { return getModeLevel_v2(); } function getModeLevel_v2() public onlyOwner view returns (uint) { Epoch storage epoch = epochs_[(epoch_id_v2_ - 2) % 3]; require(epoch.phase_v2 == Phase.RECLAIM, "gm1"); uint mode_level = LEVEL_MAX; uint max_deposit = 0; uint max_count = 0; for (uint level = 0; level < LEVEL_MAX; level++) { if (epoch.votes[level].count_v2 > 0 && (mode_level == LEVEL_MAX || max_deposit < epoch.votes[level].deposit_v2 || (max_deposit == epoch.votes[level].deposit_v2 && max_count < epoch.votes[level].count_v2))){ max_deposit = epoch.votes[level].deposit_v2; max_count = epoch.votes[level].count_v2; mode_level = level; } } return mode_level; } // Return the ownership of the JohnLawCoin contract to the ACB. // // Parameters // ---------------- // |coin|: The JohnLawCoin contract. // // Returns // ---------------- // None. function revokeOwnership(JohnLawCoin_v2 coin) public onlyOwner { return revokeOwnership_v2(coin); } function revokeOwnership_v2(JohnLawCoin_v2 coin) public onlyOwner { coin.transferOwnership(msg.sender); } // Public getter: Return the Vote object at |epoch_index| and |level|. function getVote(uint epoch_index, uint level) public view returns (uint, uint, bool, bool) { require(0 <= epoch_index && epoch_index <= 2, "gv1"); require(0 <= level && level < LEVEL_MAX, "gv2"); Vote memory vote = epochs_[epoch_index].votes[level]; return (vote.deposit_v2, vote.count_v2, vote.should_reclaim_v2, vote.should_reward_v2); } // Public getter: Return the Commit object at |epoch_index| and |account|. function getCommit(uint epoch_index, address account) public view returns (bytes32, uint, uint, Phase, uint) { require(0 <= epoch_index && epoch_index <= 2, "gc1"); Commit memory entry = epochs_[epoch_index].commits[account]; return (entry.hash, entry.deposit, entry.oracle_level, entry.phase, entry.epoch_id); } // Public getter: Return the Epoch object at |epoch_index|. function getEpoch(uint epoch_index) public view returns (address, address, uint, Phase) { require(0 <= epoch_index && epoch_index <= 2, "ge1"); return (epochs_[epoch_index].deposit_account_v2, epochs_[epoch_index].reward_account_v2, epochs_[epoch_index].reward_total_v2, epochs_[epoch_index].phase_v2); } // Calculate a hash to be committed. Voters are expected to use this function // to create a hash used in the commit phase. // // Parameters // ---------------- // |sender|: The voter's account. // |level|: The oracle level to vote. // |salt|: The voter's salt. // // Returns // ---------------- // The calculated hash value. function encrypt(address sender, uint level, uint salt) public pure returns (bytes32) { return hash_v2(sender, level, salt); } function hash_v2(address sender, uint level, uint salt) public pure returns (bytes32) { return keccak256(abi.encode(sender, level, salt)); } } //------------------------------------------------------------------------------ // [Logging contract] // // The Logging contract records various metrics for analysis purpose. // // Permission: Except public getters, only the ACB can call the methods. //------------------------------------------------------------------------------ contract Logging_v2 is OwnableUpgradeable { using SafeCast for uint; using SafeCast for int; // A struct to record metrics about voting. struct VoteLog { uint commit_succeeded; uint commit_failed; uint reveal_succeeded; uint reveal_failed; uint reclaim_succeeded; uint reward_succeeded; uint deposited; uint reclaimed; uint rewarded; uint new_value1; uint new_value2; uint new_value3; uint new_value4; } // A struct to record metrics about Epoch. struct EpochLog { uint minted_coins; uint burned_coins; int coin_supply_delta; uint total_coin_supply; uint oracle_level; uint current_epoch_start; uint tax; uint new_value1; uint new_value2; } // A struct to record metrics about BondOperation. struct BondOperationLog { int bond_budget; uint total_bond_supply; uint valid_bond_supply; uint purchased_bonds; uint redeemed_bonds; uint expired_bonds; uint new_value1; uint new_value2; } // A struct to record metrics about OpenMarketOperation. struct OpenMarketOperationLog { int coin_budget; int exchanged_coins; int exchanged_eth; uint eth_balance; uint latest_price; uint new_value1; uint new_value2; } struct AnotherLog { uint new_value1; uint new_value2; uint new_value3; uint new_value4; } // Attributes. // Logs about voting. mapping (uint => VoteLog) public vote_logs_; // Logs about Epoch. mapping (uint => EpochLog) public epoch_logs_; // Logs about BondOperation. mapping (uint => BondOperationLog) public bond_operation_logs_; // Logs about OpenMarketOperation. mapping (uint => OpenMarketOperationLog) public open_market_operation_logs_; mapping (uint => AnotherLog) public another_logs_; function upgrade() public onlyOwner { } // Public getter: Return the VoteLog of |epoch_id|. function getVoteLog(uint epoch_id) public view returns ( uint, uint, uint, uint, uint, uint, uint, uint, uint) { return getVoteLog_v2(epoch_id); } function getVoteLog_v2(uint epoch_id) public view returns ( uint, uint, uint, uint, uint, uint, uint, uint, uint) { VoteLog memory log = vote_logs_[epoch_id]; return (log.commit_succeeded, log.commit_failed, log.reveal_succeeded, log.reveal_failed, log.reclaim_succeeded, log.reward_succeeded, log.deposited, log.reclaimed, log.rewarded); } // Public getter: Return the EpochLog of |epoch_id|. function getEpochLog(uint epoch_id) public view returns (uint, uint, int, uint, uint, uint, uint) { return getEpochLog_v2(epoch_id); } function getEpochLog_v2(uint epoch_id) public view returns (uint, uint, int, uint, uint, uint, uint) { EpochLog memory log = epoch_logs_[epoch_id]; return (log.minted_coins, log.burned_coins, log.coin_supply_delta, log.total_coin_supply, log.oracle_level, log.current_epoch_start, log.tax); } // Public getter: Return the BondOperationLog of |epoch_id|. function getBondOperationLog(uint epoch_id) public view returns (int, uint, uint, uint, uint, uint) { return getBondOperationLog_v2(epoch_id); } function getBondOperationLog_v2(uint epoch_id) public view returns (int, uint, uint, uint, uint, uint) { BondOperationLog memory log = bond_operation_logs_[epoch_id]; return (log.bond_budget, log.total_bond_supply, log.valid_bond_supply, log.purchased_bonds, log.redeemed_bonds, log.expired_bonds); } // Public getter: Return the OpenMarketOperationLog of |epoch_id|. function getOpenMarketOperationLog(uint epoch_id) public view returns (int, int, int, uint, uint) { return getOpenMarketOperationLog_v2(epoch_id); } function getOpenMarketOperationLog_v2(uint epoch_id) public view returns (int, int, int, uint, uint) { OpenMarketOperationLog memory log = open_market_operation_logs_[epoch_id]; return (log.coin_budget, log.exchanged_coins, log.exchanged_eth, log.eth_balance, log.latest_price); } // Called when the epoch is updated. // // Parameters // ---------------- // |epoch_id|: The epoch ID. // |minted|: The amount of the minted coins. // |burned|: The amount of the burned coins. // |delta|: The delta of the total coin supply. // |total_coin_supply|: The total coin supply. // |oracle_level|: ACB.oracle_level_. // |current_epoch_start|: ACB.current_epoch_start_. // |tax|: The amount of the tax collected in the previous epoch. // // Returns // ---------------- // None. function updateEpoch(uint epoch_id, uint minted, uint burned, int delta, uint total_coin_supply, uint oracle_level, uint current_epoch_start, uint tax) public onlyOwner { updateEpoch_v2(epoch_id, minted, burned, delta, total_coin_supply, oracle_level, current_epoch_start, tax); } function updateEpoch_v2(uint epoch_id, uint minted, uint burned, int delta, uint total_coin_supply, uint oracle_level, uint current_epoch_start, uint tax) public onlyOwner { epoch_logs_[epoch_id].minted_coins = minted; epoch_logs_[epoch_id].burned_coins = burned; epoch_logs_[epoch_id].coin_supply_delta = delta; epoch_logs_[epoch_id].total_coin_supply = total_coin_supply; epoch_logs_[epoch_id].oracle_level = oracle_level; epoch_logs_[epoch_id].current_epoch_start = current_epoch_start; epoch_logs_[epoch_id].tax = tax; epoch_logs_[epoch_id].new_value1 += minted; epoch_logs_[epoch_id].new_value2 += burned; another_logs_[epoch_id].new_value1 += minted; another_logs_[epoch_id].new_value2 += burned; } // Called when BondOperation's bond budget is updated at the beginning of // the epoch. // // Parameters // ---------------- // |epoch_id|: The epoch ID. // |bond_budget|: The bond budget. // |total_bond_supply|: The total bond supply. // |valid_bond_supply|: The valid bond supply. // // Returns // ---------------- // None. function updateBondBudget(uint epoch_id, int bond_budget, uint total_bond_supply, uint valid_bond_supply) public onlyOwner { updateBondBudget_v2(epoch_id, bond_budget, total_bond_supply, valid_bond_supply); } function updateBondBudget_v2(uint epoch_id, int bond_budget, uint total_bond_supply, uint valid_bond_supply) public onlyOwner { bond_operation_logs_[epoch_id].bond_budget = bond_budget; bond_operation_logs_[epoch_id].total_bond_supply = total_bond_supply; bond_operation_logs_[epoch_id].valid_bond_supply = valid_bond_supply; bond_operation_logs_[epoch_id].purchased_bonds = 0; bond_operation_logs_[epoch_id].redeemed_bonds = 0; bond_operation_logs_[epoch_id].expired_bonds = 0; bond_operation_logs_[epoch_id].new_value1 = epoch_id; bond_operation_logs_[epoch_id].new_value2 = epoch_id; another_logs_[epoch_id].new_value1 += epoch_id; another_logs_[epoch_id].new_value2 += epoch_id; } // Called when OpenMarketOperation's coin budget is updated at the beginning // of the epoch. // // Parameters // ---------------- // |epoch_id|: The epoch ID. // |coin_budget|: The coin budget. // |eth_balance|: The ETH balance in the EthPool. // |latest_price|: The latest ETH / JLC price. // // Returns // ---------------- // None. function updateCoinBudget(uint epoch_id, int coin_budget, uint eth_balance, uint latest_price) public onlyOwner { updateCoinBudget_v2(epoch_id, coin_budget, eth_balance, latest_price); } function updateCoinBudget_v2(uint epoch_id, int coin_budget, uint eth_balance, uint latest_price) public onlyOwner { open_market_operation_logs_[epoch_id].coin_budget = coin_budget; open_market_operation_logs_[epoch_id].exchanged_coins = 0; open_market_operation_logs_[epoch_id].exchanged_eth = 0; open_market_operation_logs_[epoch_id].eth_balance = eth_balance; open_market_operation_logs_[epoch_id].latest_price = latest_price; open_market_operation_logs_[epoch_id].new_value1 = epoch_id; open_market_operation_logs_[epoch_id].new_value2 = epoch_id; another_logs_[epoch_id].new_value1 += epoch_id; another_logs_[epoch_id].new_value2 += epoch_id; } // Called when ACB.vote is called. // // Parameters // ---------------- // |epoch_id|: The epoch ID. // |commit_result|: Whether the commit succeeded or not. // |reveal_result|: Whether the reveal succeeded or not. // |deposited|: The amount of the deposited coins. // |reclaimed|: The amount of the reclaimed coins. // |rewarded|: The amount of the reward. // // Returns // ---------------- // None. function vote(uint epoch_id, bool commit_result, bool reveal_result, uint deposit, uint reclaimed, uint rewarded) public onlyOwner { vote_v2(epoch_id, commit_result, reveal_result, deposit, reclaimed, rewarded); } function vote_v2(uint epoch_id, bool commit_result, bool reveal_result, uint deposit, uint reclaimed, uint rewarded) public onlyOwner { if (commit_result) { vote_logs_[epoch_id].commit_succeeded += 1; } else { vote_logs_[epoch_id].commit_failed += 1; } if (reveal_result) { vote_logs_[epoch_id].reveal_succeeded += 1; } else { vote_logs_[epoch_id].reveal_failed += 1; } if (reclaimed > 0) { vote_logs_[epoch_id].reclaim_succeeded += 1; } if (rewarded > 0) { vote_logs_[epoch_id].reward_succeeded += 1; } vote_logs_[epoch_id].deposited += deposit; vote_logs_[epoch_id].reclaimed += reclaimed; vote_logs_[epoch_id].rewarded += rewarded; vote_logs_[epoch_id].new_value1 += deposit; vote_logs_[epoch_id].new_value2 += reclaimed; another_logs_[epoch_id].new_value1 += deposit; another_logs_[epoch_id].new_value2 += reclaimed; } // Called when ACB.purchaseBonds is called. // // Parameters // ---------------- // |epoch_id|: The epoch ID. // |purchased_bonds|: The number of purchased bonds. // // Returns // ---------------- // None. function purchaseBonds(uint epoch_id, uint purchased_bonds) public onlyOwner { purchaseBonds_v2(epoch_id, purchased_bonds); } function purchaseBonds_v2(uint epoch_id, uint purchased_bonds) public onlyOwner { bond_operation_logs_[epoch_id].purchased_bonds += purchased_bonds; bond_operation_logs_[epoch_id].new_value1 += purchased_bonds; } // Called when ACB.redeemBonds is called. // // Parameters // ---------------- // |epoch_id|: The epoch ID. // |redeemed_bonds|: The number of redeemded bonds. // |expired_bonds|: The number of expired bonds. // // Returns // ---------------- // None. function redeemBonds(uint epoch_id, uint redeemed_bonds, uint expired_bonds) public onlyOwner { redeemBonds_v2(epoch_id, redeemed_bonds, expired_bonds); } function redeemBonds_v2(uint epoch_id, uint redeemed_bonds, uint expired_bonds) public onlyOwner { bond_operation_logs_[epoch_id].redeemed_bonds += redeemed_bonds; bond_operation_logs_[epoch_id].expired_bonds += expired_bonds; bond_operation_logs_[epoch_id].new_value1 += redeemed_bonds; bond_operation_logs_[epoch_id].new_value2 += expired_bonds; } // Called when ACB.purchaseCoins is called. // // Parameters // ---------------- // |epoch_id|: The epoch ID. // |eth_amount|: The amount of ETH exchanged. // |coin_amount|: The amount of coins exchanged. // // Returns // ---------------- // None. function purchaseCoins(uint epoch_id, uint eth_amount, uint coin_amount) public onlyOwner { purchaseCoins_v2(epoch_id, eth_amount, coin_amount); } function purchaseCoins_v2(uint epoch_id, uint eth_amount, uint coin_amount) public onlyOwner { open_market_operation_logs_[epoch_id].exchanged_eth += eth_amount.toInt256(); open_market_operation_logs_[epoch_id].exchanged_coins += coin_amount.toInt256(); open_market_operation_logs_[epoch_id].new_value1 += eth_amount; open_market_operation_logs_[epoch_id].new_value2 += coin_amount; } // Called when ACB.sellCoins is called. // // Parameters // ---------------- // |epoch_id|: The epoch ID. // |eth_amount|: The amount of ETH exchanged. // |coin_amount|: The amount of coins exchanged. // // Returns // ---------------- // None. function sellCoins(uint epoch_id, uint eth_amount, uint coin_amount) public onlyOwner { sellCoins_v2(epoch_id, eth_amount, coin_amount); } function sellCoins_v2(uint epoch_id, uint eth_amount, uint coin_amount) public onlyOwner { open_market_operation_logs_[epoch_id].exchanged_eth -= eth_amount.toInt256(); open_market_operation_logs_[epoch_id].exchanged_coins -= coin_amount.toInt256(); open_market_operation_logs_[epoch_id].new_value1 += eth_amount; open_market_operation_logs_[epoch_id].new_value2 += coin_amount; } } //------------------------------------------------------------------------------ // [BondOperation contract] // // The BondOperation contract increases / decreases the total coin supply by // redeeming / issuing bonds. The bond budget is updated by the ACB every epoch. // // Permission: Except public getters, only the ACB can call the methods. //------------------------------------------------------------------------------ contract BondOperation_v2 is OwnableUpgradeable { using SafeCast for uint; using SafeCast for int; // Constants. The values are defined in initialize(). The values never change // during the contract execution but use 'public' (instead of 'constant') // because tests want to override the values. uint public BOND_PRICE; uint public BOND_REDEMPTION_PRICE; uint public BOND_REDEMPTION_PERIOD; uint public BOND_REDEEMABLE_PERIOD; // Attributes. See the comment in initialize(). JohnLawBond public bond_; int public bond_budget_; JohnLawBond_v2 public bond_v2_; int public bond_budget_v2_; // Events. event IncreaseBondSupplyEvent(address indexed sender, uint indexed epoch_id, uint issued_bonds, uint redemption_epoch); event DecreaseBondSupplyEvent(address indexed sender, uint indexed epoch_id, uint redeemed_bonds, uint expired_bonds); event UpdateBondBudgetEvent(uint indexed epoch_id, int delta, int bond_budget, uint mint); function upgrade(JohnLawBond_v2 bond) public onlyOwner { bond_v2_ = bond; bond_budget_v2_ = bond_budget_; bond_v2_.upgrade(); } // Deprecate the contract. function deprecate() public onlyOwner { bond_v2_.transferOwnership(msg.sender); } // Increase the total bond supply by issuing bonds. // // Parameters // ---------------- // |count|: The number of bonds to be issued. // |epoch_id|: The current epoch ID. // |coin|: The JohnLawCoin contract. The ownership needs to be transferred to // this contract. // // Returns // ---------------- // The redemption epoch of the issued bonds if it succeeds. 0 otherwise. function increaseBondSupply(address sender, uint count, uint epoch_id, JohnLawCoin_v2 coin) public onlyOwner returns (uint) { return increaseBondSupply_v2(sender, count, epoch_id, coin); } function increaseBondSupply_v2(address sender, uint count, uint epoch_id, JohnLawCoin_v2 coin) public onlyOwner returns (uint) { require(count > 0, "BondOperation: You must purchase at least one bond."); require(bond_budget_v2_ >= count.toInt256(), "BondOperation: The bond budget is not enough."); uint amount = BOND_PRICE * count; require(coin.balanceOf(sender) >= amount, "BondOperation: Your coin balance is not enough."); // Set the redemption epoch of the bonds. uint redemption_epoch = epoch_id + BOND_REDEMPTION_PERIOD; // Issue new bonds. bond_v2_.mint(sender, redemption_epoch, count); bond_budget_v2_ -= count.toInt256(); require(bond_budget_v2_ >= 0, "pb1"); require(bond_v2_.balanceOf(sender, redemption_epoch) > 0, "pb2"); // Burn the corresponding coins. coin.burn(sender, amount); bond_budget_ = bond_budget_v2_; emit IncreaseBondSupplyEvent(sender, epoch_id, count, redemption_epoch); return redemption_epoch; } // Decrease the total bond supply by redeeming bonds. // // Parameters // ---------------- // |redemption_epochs|: An array of bonds to be redeemed. The bonds are // identified by their redemption epochs. // |epoch_id|: The current epoch ID. // |coin|: The JohnLawCoin contract. The ownership needs to be transferred to // this contract. // // Returns // ---------------- // A tuple of two values: // - The number of redeemed bonds. // - The number of expired bonds. function decreaseBondSupply(address sender, uint[] memory redemption_epochs, uint epoch_id, JohnLawCoin_v2 coin) public onlyOwner returns (uint, uint) { return decreaseBondSupply_v2(sender, redemption_epochs, epoch_id, coin); } function decreaseBondSupply_v2(address sender, uint[] memory redemption_epochs, uint epoch_id, JohnLawCoin_v2 coin) public onlyOwner returns (uint, uint) { uint redeemed_bonds = 0; uint expired_bonds = 0; for (uint i = 0; i < redemption_epochs.length; i++) { uint redemption_epoch = redemption_epochs[i]; uint count = bond_v2_.balanceOf(sender, redemption_epoch); if (epoch_id < redemption_epoch) { // If the bonds have not yet hit their redemption epoch, the // BondOperation accepts the redemption as long as |bond_budget_| is // negative. if (bond_budget_v2_ >= 0) { continue; } if (count > (-bond_budget_v2_).toUint256()) { count = (-bond_budget_v2_).toUint256(); } bond_budget_v2_ += count.toInt256(); } if (epoch_id < redemption_epoch + BOND_REDEEMABLE_PERIOD) { // If the bonds are not expired, mint the corresponding coins to the // sender account. uint amount = count * BOND_REDEMPTION_PRICE; coin.mint(sender, amount); redeemed_bonds += count; } else { expired_bonds += count; } // Burn the redeemed / expired bonds. bond_v2_.burn(sender, redemption_epoch, count); } bond_budget_ = bond_budget_v2_; emit DecreaseBondSupplyEvent(sender, epoch_id, redeemed_bonds, expired_bonds); return (redeemed_bonds, expired_bonds); } // Update the bond budget to increase or decrease the total coin supply. // // Parameters // ---------------- // |delta|: The target increase or decrease of the total coin supply. // |epoch_id|: The current epoch ID. // // Returns // ---------------- // The amount of coins that cannot be increased by adjusting the bond budget // and thus need to be newly minted. function updateBondBudget(int delta, uint epoch_id) public onlyOwner returns (uint) { return updateBondBudget_v2(delta, epoch_id); } function updateBondBudget_v2(int delta, uint epoch_id) public onlyOwner returns (uint) { uint mint = 0; uint bond_supply = validBondSupply(epoch_id); if (delta == 0) { // No change in the total coin supply. bond_budget_v2_ = 0; } else if (delta > 0) { // Increase the total coin supply. uint count = delta.toUint256() / BOND_REDEMPTION_PRICE; if (count <= bond_supply) { // If there are sufficient bonds to redeem, increase the total coin // supply by redeeming the bonds. bond_budget_v2_ = -count.toInt256(); } else { // Otherwise, redeem all the issued bonds. bond_budget_v2_ = -bond_supply.toInt256(); // The remaining coins need to be newly minted. mint = (count - bond_supply) * BOND_REDEMPTION_PRICE; } require(bond_budget_v2_ <= 0, "cs1"); } else { // Issue new bonds to decrease the total coin supply. bond_budget_v2_ = -delta / BOND_PRICE.toInt256(); require(bond_budget_v2_ >= 0, "cs2"); } bond_budget_ = bond_budget_v2_; require(bond_supply.toInt256() + bond_budget_v2_ >= 0, "cs3"); emit UpdateBondBudgetEvent(epoch_id, delta, bond_budget_v2_, mint); return mint; } // Public getter: Return the valid bond supply; i.e., the total supply of // not-yet-expired bonds. function validBondSupply(uint epoch_id) public view returns (uint) { return validBondSupply_v2(epoch_id); } function validBondSupply_v2(uint epoch_id) public view returns (uint) { uint count = 0; for (uint redemption_epoch = (epoch_id > BOND_REDEEMABLE_PERIOD ? epoch_id - BOND_REDEEMABLE_PERIOD + 1 : 0); // The previous versions of the smart contract might have used a larger // BOND_REDEMPTION_PERIOD. Add 20 to look up all the redemption // epochs that might have set in the previous versions. redemption_epoch <= epoch_id + BOND_REDEMPTION_PERIOD + 20; redemption_epoch++) { count += bond_v2_.bondSupplyAt(redemption_epoch); } return count; } // Return the ownership of the JohnLawCoin contract to the ACB. // // Parameters // ---------------- // |coin|: The JohnLawCoin contract. // // Returns // ---------------- // None. function revokeOwnership(JohnLawCoin_v2 coin) public onlyOwner { return revokeOwnership_v2(coin); } function revokeOwnership_v2(JohnLawCoin_v2 coin) public onlyOwner { coin.transferOwnership(msg.sender); } } //------------------------------------------------------------------------------ // [OpenMarketOperation contract] // // The OpenMarketOperation contract increases / decreases the total coin supply // by purchasing / selling ETH from the open market. The price between JLC and // ETH is determined by a Dutch auction. // // Permission: Except public getters, only the ACB can call the methods. //------------------------------------------------------------------------------ contract OpenMarketOperation_v2 is OwnableUpgradeable { using SafeCast for uint; using SafeCast for int; // Constants. The values are defined in initialize(). The values never change // during the contract execution but use 'public' (instead of 'constant') // because tests want to override the values. uint public PRICE_CHANGE_INTERVAL; uint public PRICE_CHANGE_PERCENTAGE; uint public PRICE_CHANGE_MAX; uint public PRICE_MULTIPLIER; // Attributes. See the comment in initialize(). uint public latest_price_; bool public latest_price_updated_; uint public start_price_; int public coin_budget_; uint public latest_price_v2_; bool public latest_price_updated_v2_; uint public start_price_v2_; int public coin_budget_v2_; // Events. event IncreaseCoinSupplyEvent(uint requested_eth_amount, uint elapsed_time, uint eth_amount, uint coin_amount); event DecreaseCoinSupplyEvent(uint requested_coin_amount, uint elapsed_time, uint eth_balance, uint eth_amount, uint coin_amount); event UpdateCoinBudgetEvent(int coin_budget); function upgrade() public onlyOwner { latest_price_v2_ = latest_price_; latest_price_updated_v2_ = latest_price_updated_; start_price_v2_ = start_price_; coin_budget_v2_ = coin_budget_; } // Increase the total coin supply by purchasing ETH from the sender account. // This method returns the amount of JLC and ETH to be exchanged. The actual // change to the total coin supply and the ETH pool is made by the ACB. // // Parameters // ---------------- // |requested_eth_amount|: The amount of ETH the sender is willing to pay. // |elapsed_time|: The elapsed seconds from the current epoch start. // // Returns // ---------------- // A tuple of two values: // - The amount of ETH to be exchanged. This can be smaller than // |requested_eth_amount| when the open market operation does not have // enough coin budget. // - The amount of JLC to be exchanged. function increaseCoinSupply(uint requested_eth_amount, uint elapsed_time) public onlyOwner returns (uint, uint) { return increaseCoinSupply_v2(requested_eth_amount, elapsed_time); } function increaseCoinSupply_v2(uint requested_eth_amount, uint elapsed_time) public onlyOwner returns (uint, uint) { require(coin_budget_v2_ > 0, "OpenMarketOperation: The coin budget must be positive."); // Calculate the amount of JLC and ETH to be exchanged. uint price = getCurrentPrice(elapsed_time); uint coin_amount = requested_eth_amount / price; if (coin_amount > coin_budget_v2_.toUint256()) { coin_amount = coin_budget_v2_.toUint256(); } uint eth_amount = coin_amount * price; if (coin_amount > 0) { latest_price_v2_ = price; latest_price_updated_v2_ = true; } coin_budget_v2_ -= coin_amount.toInt256(); require(coin_budget_v2_ >= 0, "ic1"); require(eth_amount <= requested_eth_amount, "ic2"); emit IncreaseCoinSupplyEvent(requested_eth_amount, elapsed_time, eth_amount, coin_amount); latest_price_ = latest_price_v2_; latest_price_updated_ = latest_price_updated_v2_; start_price_ = start_price_v2_; coin_budget_ = coin_budget_v2_; return (eth_amount, coin_amount); } // Decrease the total coin supply by selling ETH to the sender account. // This method returns the amount of JLC and ETH to be exchanged. The actual // change to the total coin supply and the ETH pool is made by the ACB. // // Parameters // ---------------- // |requested_coin_amount|: The amount of JLC the sender is willing to pay. // |elapsed_time|: The elapsed seconds from the current epoch start. // |eth_balance|: The ETH balance in the EthPool. // // Returns // ---------------- // A tuple of two values: // - The amount of ETH to be exchanged. // - The amount of JLC to be exchanged. This can be smaller than // |requested_coin_amount| when the open market operation does not have // enough ETH in the pool. function decreaseCoinSupply(uint requested_coin_amount, uint elapsed_time, uint eth_balance) public onlyOwner returns (uint, uint) { return decreaseCoinSupply_v2(requested_coin_amount, elapsed_time, eth_balance); } function decreaseCoinSupply_v2(uint requested_coin_amount, uint elapsed_time, uint eth_balance) public onlyOwner returns (uint, uint) { require(coin_budget_v2_ < 0, "OpenMarketOperation: The coin budget must be negative."); // Calculate the amount of JLC and ETH to be exchanged. uint price = getCurrentPrice(elapsed_time); uint coin_amount = requested_coin_amount; if (coin_amount >= (-coin_budget_v2_).toUint256()) { coin_amount = (-coin_budget_v2_).toUint256(); } uint eth_amount = coin_amount * price; if (eth_amount >= eth_balance) { eth_amount = eth_balance; } coin_amount = eth_amount / price; if (coin_amount > 0) { latest_price_v2_ = price; latest_price_updated_v2_ = true; } coin_budget_v2_ += coin_amount.toInt256(); require(coin_budget_v2_ <= 0, "dc1"); require(coin_amount <= requested_coin_amount, "dc2"); emit DecreaseCoinSupplyEvent(requested_coin_amount, elapsed_time, eth_balance, eth_amount, coin_amount); latest_price_ = latest_price_v2_; latest_price_updated_ = latest_price_updated_v2_; start_price_ = start_price_v2_; coin_budget_ = coin_budget_v2_; return (eth_amount, coin_amount); } // Return the current price in the Dutch auction. // // Parameters // ---------------- // |elapsed_time|: The elapsed seconds from the current epoch start. // // Returns // ---------------- // The current price. function getCurrentPrice(uint elapsed_time) public view returns (uint) { return getCurrentPrice_v2(elapsed_time); } function getCurrentPrice_v2(uint elapsed_time) public view returns (uint) { if (coin_budget_v2_ > 0) { uint price = start_price_v2_; for (uint i = 0; i < elapsed_time / PRICE_CHANGE_INTERVAL && i < PRICE_CHANGE_MAX; i++) { price = price * (100 - PRICE_CHANGE_PERCENTAGE) / 100; } if (price == 0) { price = 1; } return price; } else if (coin_budget_v2_ < 0) { uint price = start_price_v2_; for (uint i = 0; i < elapsed_time / PRICE_CHANGE_INTERVAL && i < PRICE_CHANGE_MAX; i++) { price = price * (100 + PRICE_CHANGE_PERCENTAGE) / 100; } return price; } return 0; } // Update the coin budget. The coin budget indicates how many coins should // be added to / removed from the total coin supply; i.e., the amount of JLC // to be sold / purchased by the open market operation. The ACB calls the // method at the beginning of each epoch. // // Parameters // ---------------- // |coin_budget|: The coin budget. // // Returns // ---------------- // None. function updateCoinBudget(int coin_budget) public onlyOwner { updateCoinBudget_v2(coin_budget); } function updateCoinBudget_v2(int coin_budget) public onlyOwner { if (latest_price_updated_v2_ == false) { if (coin_budget_v2_ > 0) { // If no exchange was observed in the previous epoch, the price setting // was too high. Lower the price. latest_price_v2_ = latest_price_v2_ / PRICE_MULTIPLIER + 1; } else if (coin_budget_v2_ < 0) { // If no exchange was observed in the previous epoch, the price setting // was too low. Raise the price. latest_price_v2_ = latest_price_v2_ * PRICE_MULTIPLIER; } } coin_budget_v2_ = coin_budget; latest_price_updated_v2_ = false; require(latest_price_v2_ > 0, "uc1"); if (coin_budget_v2_ > 0) { start_price_v2_ = latest_price_v2_ * PRICE_MULTIPLIER; } else if (coin_budget_v2_ == 0) { start_price_v2_ = 0; } else { start_price_v2_ = latest_price_v2_ / PRICE_MULTIPLIER + 1; } emit UpdateCoinBudgetEvent(coin_budget_v2_); latest_price_ = latest_price_v2_; latest_price_updated_ = latest_price_updated_v2_; start_price_ = start_price_v2_; coin_budget_ = coin_budget_v2_; } } //------------------------------------------------------------------------------ // [EthPool contract] // // The EthPool contract stores ETH for the open market operation. // // Permission: Except public getters, only the ACB can call the methods. //------------------------------------------------------------------------------ contract EthPool_v2 is OwnableUpgradeable { function upgrade() public onlyOwner { } // Increase ETH. function increaseEth() public onlyOwner payable { increaseEth_v2(); } function increaseEth_v2() public onlyOwner payable { } // Decrease |eth_amount| ETH and send it to the |receiver|. function decreaseEth(address receiver, uint eth_amount) public onlyOwner { decreaseEth_v2(receiver, eth_amount); } function decreaseEth_v2(address receiver, uint eth_amount) public onlyOwner { require(address(this).balance >= eth_amount, "de1"); (bool success,) = payable(receiver).call{value: eth_amount}(""); require(success, "de2"); } } //------------------------------------------------------------------------------ // [ACB contract] // // The ACB stabilizes the USD / JLC exchange rate to 1.0 with algorithmically // defined monetary policies: // // 1. The ACB obtains the exchange rate from the oracle. // 2. If the exchange rate is 1.0, the ACB does nothing. // 3. If the exchange rate is higher than 1.0, the ACB increases the total coin // supply by redeeming issued bonds (regardless of their redemption dates). // If that is not enough to supply sufficient coins, the ACB performs an open // market operation to sell JLC and purchase ETH to increase the total coin // supply. // 4. If the exchange rate is lower than 1.0, the ACB decreases the total coin // supply by issuing new bonds. If the exchange rate drops down to 0.6, the // ACB performs an open market operation to sell ETH and purchase JLC to // decrease the total coin supply. // // Permission: All the methods are public. No one (including the genesis // account) is privileged to influence the monetary policies of the ACB. The ACB // is fully decentralized and there is truly no gatekeeper. The only exceptions // are a few methods the genesis account may use to upgrade the smart contracts // to fix bugs during a development phase. //------------------------------------------------------------------------------ contract ACB_v2 is OwnableUpgradeable, PausableUpgradeable { using SafeCast for uint; using SafeCast for int; bytes32 public constant NULL_HASH = 0; // Constants. The values are defined in initialize(). The values never change // during the contract execution but use 'public' (instead of 'constant') // because tests want to override the values. uint[] public LEVEL_TO_EXCHANGE_RATE; uint public EXCHANGE_RATE_DIVISOR; uint public EPOCH_DURATION; uint public DEPOSIT_RATE; uint public DAMPING_FACTOR; // Used only in testing. This cannot be put in a derived contract due to // a restriction of @openzeppelin/truffle-upgrades. uint public _timestamp_for_testing; // Attributes. See the comment in initialize(). JohnLawCoin public coin_; Oracle public oracle_; BondOperation public bond_operation_; OpenMarketOperation public open_market_operation_; EthPool public eth_pool_; Logging public logging_; uint public oracle_level_; uint public current_epoch_start_; JohnLawCoin_v2 public coin_v2_; Oracle_v2 public oracle_v2_; BondOperation_v2 public bond_operation_v2_; OpenMarketOperation_v2 public open_market_operation_v2_; EthPool_v2 public eth_pool_v2_; Logging_v2 public logging_v2_; uint public oracle_level_v2_; uint public current_epoch_start_v2_; // Events. event PayableEvent(address indexed sender, uint value); event UpdateEpochEvent(uint epoch_id, uint current_epoch_start, uint tax, uint burned, int delta, uint mint); event VoteEvent(address indexed sender, uint indexed epoch_id, bytes32 hash, uint oracle_level, uint salt, bool commit_result, bool reveal_result, uint deposited, uint reclaimed, uint rewarded, bool epoch_updated); event PurchaseBondsEvent(address indexed sender, uint indexed epoch_id, uint purchased_bonds, uint redemption_epoch); event RedeemBondsEvent(address indexed sender, uint indexed epoch_id, uint redeemed_bonds, uint expired_bonds); event PurchaseCoinsEvent(address indexed sender, uint requested_eth_amount, uint eth_amount, uint coin_amount); event SellCoinsEvent(address indexed sender, uint requested_coin_amount, uint eth_amount, uint coin_amount); function upgrade(JohnLawCoin_v2 coin, JohnLawBond_v2 bond, Oracle_v2 oracle, BondOperation_v2 bond_operation, OpenMarketOperation_v2 open_market_operation, EthPool_v2 eth_pool, Logging_v2 logging) public onlyOwner { coin_v2_ = coin; oracle_v2_ = oracle; bond_operation_v2_ = bond_operation; open_market_operation_v2_ = open_market_operation; eth_pool_v2_ = eth_pool; oracle_level_v2_ = oracle_level_; current_epoch_start_v2_ = current_epoch_start_; logging_v2_ = logging; coin_v2_.upgrade(); bond_operation_v2_.upgrade(bond); open_market_operation_v2_.upgrade(); eth_pool_v2_.upgrade(); oracle_v2_.upgrade(); logging_v2_.upgrade(); } // Deprecate the ACB. Only the genesis account can call this method. function deprecate() public onlyOwner { coin_v2_.transferOwnership(msg.sender); oracle_v2_.transferOwnership(msg.sender); bond_operation_v2_.transferOwnership(msg.sender); open_market_operation_v2_.transferOwnership(msg.sender); eth_pool_v2_.transferOwnership(msg.sender); logging_v2_.transferOwnership(msg.sender); } // Pause the ACB in emergency cases. Only the genesis account can call this // method. function pause() public onlyOwner { if (!paused()) { _pause(); } coin_v2_.pause(); } // Unpause the ACB. Only the genesis account can call this method. function unpause() public onlyOwner { if (paused()) { _unpause(); } coin_v2_.unpause(); } // Payable fallback to receive and store ETH. Give us tips :) fallback() external payable { require(msg.data.length == 0, "fb1"); emit PayableEvent(msg.sender, msg.value); } receive() external payable { emit PayableEvent(msg.sender, msg.value); } // Withdraw the tips. Only the genesis account can call this method. function withdrawTips() public whenNotPaused onlyOwner { (bool success,) = payable(msg.sender).call{value: address(this).balance}(""); require(success, "wt1"); } // A struct to pack local variables. This is needed to avoid a stack-too-deep // error in Solidity. struct VoteResult { uint epoch_id; bool epoch_updated; bool reveal_result; bool commit_result; uint deposited; uint reclaimed; uint rewarded; } // Vote for the exchange rate. The voter can commit a vote to the current // epoch N, reveal their vote in the epoch N-1, and reclaim the deposited // coins and get a reward for their vote in the epoch N-2 at the same time. // // Parameters // ---------------- // |hash|: The hash to be committed in the current epoch N. Specify // ACB.NULL_HASH if you do not want to commit and only want to reveal and // reclaim previous votes. // |oracle_level|: The oracle level you voted for in the epoch N-1. // |salt|: The salt you used in the epoch N-1. // // Returns // ---------------- // A tuple of six values: // - boolean: Whether the commit succeeded or not. // - boolean: Whether the reveal succeeded or not. // - uint: The amount of the deposited coins. // - uint: The amount of the reclaimed coins. // - uint: The amount of the reward. // - boolean: Whether this vote updated the epoch. function vote(bytes32 hash, uint oracle_level, uint salt) public whenNotPaused returns (bool, bool, uint, uint, uint, bool) { return vote_v2(hash, oracle_level, salt); } function vote_v2(bytes32 hash, uint oracle_level, uint salt) public whenNotPaused returns (bool, bool, uint, uint, uint, bool) { VoteResult memory result; result.epoch_id = oracle_v2_.epoch_id_(); result.epoch_updated = false; if (getTimestamp() >= current_epoch_start_v2_ + EPOCH_DURATION) { // Start a new epoch. result.epoch_updated = true; result.epoch_id += 1; current_epoch_start_v2_ = getTimestamp(); current_epoch_start_ = current_epoch_start_v2_; // Advance to the next epoch. Provide the |tax| coins to the oracle // as a reward. uint tax = coin_v2_.balanceOf(coin_v2_.tax_account_v2_()); coin_v2_.transferOwnership(address(oracle_v2_)); uint burned = oracle_v2_.advance(coin_v2_); oracle_v2_.revokeOwnership(coin_v2_); // Reset the tax account address just in case. coin_v2_.resetTaxAccount(); require(coin_v2_.balanceOf(coin_v2_.tax_account_v2_()) == 0, "vo1"); int delta = 0; oracle_level_ = oracle_v2_.getModeLevel(); if (oracle_level_ != oracle_v2_.LEVEL_MAX()) { require(0 <= oracle_level_ && oracle_level_ < oracle_v2_.LEVEL_MAX(), "vo2"); // Translate the oracle level to the exchange rate. uint exchange_rate = LEVEL_TO_EXCHANGE_RATE[oracle_level_]; // Calculate the amount of coins to be minted or burned based on the // Quantity Theory of Money. If the exchange rate is 1.1 (i.e., 1 coin // = 1.1 USD), the total coin supply is increased by 10%. If the // exchange rate is 0.8 (i.e., 1 coin = 0.8 USD), the total coin supply // is decreased by 20%. delta = coin_v2_.totalSupply().toInt256() * (int(exchange_rate) - int(EXCHANGE_RATE_DIVISOR)) / int(EXCHANGE_RATE_DIVISOR); // To avoid increasing or decreasing too many coins in one epoch, // multiply the damping factor. delta = delta * int(DAMPING_FACTOR) / 100; } // Update the bond budget. uint mint = bond_operation_v2_.updateBondBudget(delta, result.epoch_id); // Update the coin budget. if (oracle_level_ == 0 && delta < 0) { require(mint == 0, "vo3"); open_market_operation_v2_.updateCoinBudget(delta); } else { open_market_operation_v2_.updateCoinBudget(mint.toInt256()); } logging_v2_.updateEpoch( result.epoch_id, mint, burned, delta, coin_v2_.totalSupply(), oracle_level_, current_epoch_start_v2_, tax); logging_v2_.updateBondBudget( result.epoch_id, bond_operation_v2_.bond_budget_v2_(), bond_operation_v2_.bond_v2_().totalSupply(), bond_operation_v2_.validBondSupply(result.epoch_id)); logging_v2_.updateCoinBudget( result.epoch_id, open_market_operation_v2_.coin_budget_v2_(), address(eth_pool_).balance, open_market_operation_v2_.latest_price_()); emit UpdateEpochEvent(result.epoch_id, current_epoch_start_v2_, tax, burned, delta, mint); } coin_v2_.transferOwnership(address(oracle_v2_)); // Commit. // // The voter needs to deposit the DEPOSIT_RATE percentage of their coin // balance. result.deposited = coin_v2_.balanceOf(msg.sender) * DEPOSIT_RATE / 100; if (hash == 0) { result.deposited = 0; } result.commit_result = oracle_v2_.commit( msg.sender, hash, result.deposited, coin_v2_); if (!result.commit_result) { result.deposited = 0; } // Reveal. result.reveal_result = oracle_v2_.reveal(msg.sender, oracle_level, salt); // Reclaim. (result.reclaimed, result.rewarded) = oracle_v2_.reclaim(msg.sender, coin_v2_); oracle_v2_.revokeOwnership(coin_v2_); logging_v2_.vote(result.epoch_id, result.commit_result, result.reveal_result, result.deposited, result.reclaimed, result.rewarded); emit VoteEvent( msg.sender, result.epoch_id, hash, oracle_level, salt, result.commit_result, result.reveal_result, result.deposited, result.reclaimed, result.rewarded, result.epoch_updated); return (result.commit_result, result.reveal_result, result.deposited, result.reclaimed, result.rewarded, result.epoch_updated); } // Purchase bonds. // // Parameters // ---------------- // |count|: The number of bonds to purchase. // // Returns // ---------------- // The redemption epoch of the purchased bonds. function purchaseBonds(uint count) public whenNotPaused returns (uint) { return purchaseBonds_v2(count); } function purchaseBonds_v2(uint count) public whenNotPaused returns (uint) { uint epoch_id = oracle_v2_.epoch_id_(); coin_v2_.transferOwnership(address(bond_operation_v2_)); uint redemption_epoch = bond_operation_v2_.increaseBondSupply(address(msg.sender), count, epoch_id, coin_v2_); bond_operation_v2_.revokeOwnership(coin_v2_); logging_v2_.purchaseBonds(epoch_id, count); emit PurchaseBondsEvent(address(msg.sender), epoch_id, count, redemption_epoch); return redemption_epoch; } // Redeem bonds. // // Parameters // ---------------- // |redemption_epochs|: An array of bonds to be redeemed. The bonds are // identified by their redemption epochs. // // Returns // ---------------- // The number of successfully redeemed bonds. function redeemBonds(uint[] memory redemption_epochs) public whenNotPaused returns (uint) { return redeemBonds_v2(redemption_epochs); } function redeemBonds_v2(uint[] memory redemption_epochs) public whenNotPaused returns (uint) { uint epoch_id = oracle_v2_.epoch_id_(); coin_v2_.transferOwnership(address(bond_operation_v2_)); (uint redeemed_bonds, uint expired_bonds) = bond_operation_v2_.decreaseBondSupply( address(msg.sender), redemption_epochs, epoch_id, coin_v2_); bond_operation_v2_.revokeOwnership(coin_v2_); logging_v2_.redeemBonds(epoch_id, redeemed_bonds, expired_bonds); emit RedeemBondsEvent(address(msg.sender), epoch_id, redeemed_bonds, expired_bonds); return redeemed_bonds; } // Pay ETH and purchase JLC from the open market operation. // // Parameters // ---------------- // The sender needs to pay |requested_eth_amount| ETH. // // Returns // ---------------- // A tuple of two values: // - The amount of ETH the sender paid. This value can be smaller than // |requested_eth_amount| when the open market operation does not have enough // coin budget. The remaining ETH is returned to the sender's wallet. // - The amount of JLC the sender purchased. function purchaseCoins() public whenNotPaused payable returns (uint, uint) { uint requested_eth_amount = msg.value; uint elapsed_time = getTimestamp() - current_epoch_start_v2_; // Calculate the amount of ETH and JLC to be exchanged. (uint eth_amount, uint coin_amount) = open_market_operation_v2_.increaseCoinSupply( requested_eth_amount, elapsed_time); coin_v2_.mint(msg.sender, coin_amount); require(address(this).balance >= requested_eth_amount, "pc1"); bool success; (success,) = payable(address(eth_pool_v2_)).call{value: eth_amount}( abi.encodeWithSignature("increaseEth()")); require(success, "pc2"); logging_.purchaseCoins(oracle_.epoch_id_(), eth_amount, coin_amount); // Pay back the remaining ETH to the sender. This may trigger any arbitrary // operations in an external smart contract. This must be called at the very // end of purchaseCoins(). (success,) = payable(msg.sender).call{value: requested_eth_amount - eth_amount}(""); require(success, "pc3"); emit PurchaseCoinsEvent(msg.sender, requested_eth_amount, eth_amount, coin_amount); return (eth_amount, coin_amount); } // Pay JLC and purchase ETH from the open market operation. // // Parameters // ---------------- // |requested_coin_amount|: The amount of JLC the sender is willing to pay. // // Returns // ---------------- // A tuple of two values: // - The amount of ETH the sender purchased. // - The amount of JLC the sender paid. This value can be smaller than // |requested_coin_amount| when the open market operation does not have // enough ETH in the pool. function sellCoins(uint requested_coin_amount) public whenNotPaused returns (uint, uint) { return sellCoins_v2(requested_coin_amount); } function sellCoins_v2(uint requested_coin_amount) public whenNotPaused returns (uint, uint) { // The sender does not have enough coins. require(coin_v2_.balanceOf(msg.sender) >= requested_coin_amount, "OpenMarketOperation: Your coin balance is not enough."); // Calculate the amount of ETH and JLC to be exchanged. uint elapsed_time = getTimestamp() - current_epoch_start_v2_; (uint eth_amount, uint coin_amount) = open_market_operation_v2_.decreaseCoinSupply( requested_coin_amount, elapsed_time, address(eth_pool_v2_).balance); coin_v2_.burn(msg.sender, coin_amount); logging_.sellCoins(oracle_.epoch_id_(), eth_amount, coin_amount); // Send ETH to the sender. This may trigger any arbitrary operations in an // external smart contract. This must be called at the very end of // sellCoins(). eth_pool_v2_.decreaseEth(msg.sender, eth_amount); emit SellCoinsEvent(msg.sender, requested_coin_amount, eth_amount, coin_amount); return (eth_amount, coin_amount); } // Calculate a hash to be committed to the oracle. Voters are expected to // call this function to create the hash. // // Parameters // ---------------- // |level|: The oracle level to vote. // |salt|: The voter's salt. // // Returns // ---------------- // The calculated hash value. function encrypt(uint level, uint salt) public view returns (bytes32) { return encrypt_v2(level, salt); } function encrypt_v2(uint level, uint salt) public view returns (bytes32) { address sender = msg.sender; return oracle_v2_.encrypt(sender, level, salt); } // Public getter: Return the current timestamp in seconds. function getTimestamp() public virtual view returns (uint) { // block.timestamp is better than block.number because the granularity of // the epoch update is EPOCH_DURATION (1 week). return block.timestamp; } }
Pay ETH and purchase JLC from the open market operation. Parameters ---------------- The sender needs to pay |requested_eth_amount| ETH. Returns ---------------- A tuple of two values: - The amount of ETH the sender paid. This value can be smaller than |requested_eth_amount| when the open market operation does not have enough coin budget. The remaining ETH is returned to the sender's wallet. - The amount of JLC the sender purchased. Calculate the amount of ETH and JLC to be exchanged. Pay back the remaining ETH to the sender. This may trigger any arbitrary operations in an external smart contract. This must be called at the very end of purchaseCoins().
function purchaseCoins() public whenNotPaused payable returns (uint, uint) { uint requested_eth_amount = msg.value; uint elapsed_time = getTimestamp() - current_epoch_start_v2_; (uint eth_amount, uint coin_amount) = open_market_operation_v2_.increaseCoinSupply( requested_eth_amount, elapsed_time); coin_v2_.mint(msg.sender, coin_amount); require(address(this).balance >= requested_eth_amount, "pc1"); bool success; (success,) = abi.encodeWithSignature("increaseEth()")); require(success, "pc2"); logging_.purchaseCoins(oracle_.epoch_id_(), eth_amount, coin_amount); (success,) = require(success, "pc3"); emit PurchaseCoinsEvent(msg.sender, requested_eth_amount, eth_amount, coin_amount); return (eth_amount, coin_amount); }
13,078,088
pragma solidity ^0.6.0; import "../SortitionSumTreeFactory.sol"; /** * @title ExposedSortitionSumTreeFactory * @author Enrique Piqueras - <[email protected]> * @dev Exposed version of SortitionSumTreeFactory for testing. */ contract ExposedSortitionSumTreeFactory { /* Storage */ using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; SortitionSumTreeFactory.SortitionSumTrees internal sortitionSumTrees; /** * @dev Public getter for sortitionSumTrees. * @param _key The key of the tree to get. * @return K * @return stack * @return nodes */ function _sortitionSumTrees(bytes32 _key) public view returns(uint K, uint[] memory stack, uint[] memory nodes) { return ( sortitionSumTrees.sortitionSumTrees[_key].K, sortitionSumTrees.sortitionSumTrees[_key].stack, sortitionSumTrees.sortitionSumTrees[_key].nodes ); } /* Public */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K The number of children each node in the tree should have. */ function _createTree(bytes32 _key, uint _K) public { sortitionSumTrees.createTree(_key, _K); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. */ function _set(bytes32 _key, uint _value, bytes32 _ID) public { sortitionSumTrees.set(_key, _value, _ID); } /* Public Views */ /** * @dev Query the leaves of a tree. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return startIndex The index at which leaves start * @return values the values of the returned leaves * @return hasMore whether there are more for pagination. */ function _queryLeafs(bytes32 _key, uint _cursor, uint _count) public view returns(uint startIndex, uint[] memory values, bool hasMore) { return sortitionSumTrees.queryLeafs(_key, _cursor, _count); } /** * @dev Draw an ID from a tree using a number. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return ID The drawn ID. */ function _draw(bytes32 _key, uint _drawnNumber) public view returns(bytes32 ID) { return sortitionSumTrees.draw(_key, _drawnNumber); } /** @dev Gets a specified candidate's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return value The associated value. */ function _stakeOf(bytes32 _key, bytes32 _ID) public view returns(uint value) { return sortitionSumTrees.stakeOf(_key, _ID); } }
Draw an ID from a tree using a number. _key The key of the tree. _drawnNumber The drawn number. return ID The drawn ID./
function _draw(bytes32 _key, uint _drawnNumber) public view returns(bytes32 ID) { return sortitionSumTrees.draw(_key, _drawnNumber); }
14,108,866
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "./Token.sol"; import { Pausable } from "./utils/Ownable.sol"; import "./IERC20.sol"; import "./utils/SafeMath.sol"; import "./utils/SafeCast.sol"; import "./utils/SafeBEP20.sol"; // SOULLIB ...90% /\/\ // INTERACTIONS BETWEEN MAJOR PARTIES: CALLER // AND CALL RECEIVER. THE TERM SOULLIBEE IS // REFERRED TO AS CALL ROUTER WHILE SOULLIBER // CALL RECEIVER. // IT MODELS A // BUSI NESS // RELATION SHIP // DERIVED FROM THE SERVICE RENDERED BY THE // SOULLIBER TO THE CALLER. A FEE IS CHARGED // AGAINST THE CALLER's ACCOUNT IN "SLIB // TOKEN" WHICH IS // REGISTERED IN // FAVOUR OF SOME // BENEFI CIARIES // THUS : SOULLIBER : The caller receiver. // SOULLIB : The soullib platform. // REFEREE : One who referred a soulliber. // UPLINE: Organisation the Soullib works for // STAKER : Anyone who have staked SLIB // Token up to the minimum stakers // requirement BOARD : Anyone who have staked // SLIB Token up to the // minimum boards' requirement AT // EVERY CALL MADE A FEE IS CHARGED // REGARDED AS REVENUE. REVENU E // GENERATED FOR EACH CATEGORY IS TRACKED.WHEN A // SOULLIBEE ROUTES A CALL: WE INSTANTLY DISTRIBUTE // THE INCOME AMONGST: SOULLIBER, UPLINE, SOULLIB // REFEREE THE REST IS CHARGED TO A // LEDGER KEPT TO A PARTICULAR PERIOD // AFTER WHICH WILL BE UNLOCKED AND // ANYONE IN THE STAKER AND, BOARD // CATEGORIES CAN ONLY CLAIM THEREAFTER THIS IS BECAUSE // THE NUMBER OF THE STAKERS AND BOARD MEMBERS // CANNOT BE DETERMINED AT THE POINT A CALL ROUTED // HAPPY READING // COPYRIGHT : SOULLIB // DEV: BOBEU https://github.com/bobeu contract SlibDistributorHelper is Pausable { using SafeMath for uint256; ///@dev emits notificatio when a call is routed from @param to to @param from event CallSent(address indexed to, address indexed from); ///@dev Emits event when @param staker staked an @param amount event Staked(address indexed staker, uint256 amount); ///@dev Emits event when @param staker unstakes an @param amount event Unstaked(address indexed staker, uint256 amount); ///@dev Emits event when @param user claims an @param amount event Claimed(address indexed user, uint256 amount); ///@dev Emits event when @param newSignUp is added by an @param upline event SignedUp(address indexed newSignUp, address indexed upline); ///@dev Emits event when @param upline removed @param soulliber event Deleted(address indexed upline, address indexed soulliber); ///@notice Categories any soulliber can belong to enum Categ { INDIV, PRIV, GOV } //SubCategory enum Share { SOULLIBEE, SOULLIBER, UPLINE, SOULLIB, BOARD, STAKER, REFEREE } ///@dev Function selector : Connects with the SLIB Token contract using low level call. bytes4 private constant TOGGLE_SELECTOR = bytes4(keccak256(bytes("toggleBal(address,uint256,uint8)"))); ///@dev Structure profile data struct Prof { address upline; address referee; uint256 lastBalChanged; uint64 lastClaimedDate; uint256 stake; uint[] callIds; mapping(address=>bool) canClaimRef; mapping(Share=>bool) status; Categ cat; Share sh; } ///@dev Global/state data struct Revenue { uint64 round; uint96 withdrawWindow; uint64 lastUnlockedDate; //Last time reward was released to the pool uint perCallCharge; uint totalFeeGeneratedForARound; uint id; uint stakersShare; uint boardShare; mapping(Categ=>mapping(uint64 => uint256)) revenue; mapping(address=>uint256) shares; } ///@dev Explicit storage getter Revenue private rev; /**@dev minimumStake thresholds */ uint256[3] private thresholds; ///@dev Tracks the number of Soullibers in each category uint256[3] public counter; ///@dev SLIB Token address address public token; ///@dev Router address for governance integration address private router; ///@dev Tracks the number of time fee revenue was generated uint64 public revenueCounter = 5; ///@dev Tracks the number of stakers uint64 public stakersCount; ///@dev Tracks the number of borad greater than thresholds[1] uint64 public boardCount; ///@dev Profiles of all users mapping(address => Prof) private profs; /**@dev Sharing rates */ mapping(Categ => uint256[7]) private rates; ///@dev Ensure "target" is a not already signed up modifier isNotSoulliber(address target) { require(!isSoulliber(target), "Already signed up"); _; } ///@dev Ensure "target" is a already signed up modifier isASoulliber(address target) { require(isSoulliber(target), "Not a soulliber"); _; } ///@dev Ensure "idx" is within acceptable range modifier oneOrTwo(uint8 idx) { require(idx == 1 || idx == 2, "Out of bound"); _; } ///@dev Ensure "idx" is within acceptable range modifier lessThan3(uint8 idx) { require(idx < 3, "Out of bound"); _; } ///@dev Initialize storage and state constructor() {} /**@dev Fallback */ receive() external payable { (bool ss,) = router.call{value: msg.value}(""); require(ss,""); } /**@dev Sets sharing rate for each of the categories */ function setRate(uint8 categoryIndex, uint256[7] memory newRates) public onlyAdmin returns (bool) { //Perform check for (uint8 i = 0; i < newRates.length; i++) { require(newRates[i] < 101, "NewRate: 100% max exceed"); } rates[Categ(categoryIndex)] = newRates; return true; } ///@dev Ensures "target" is the zero address function _notZero(address target) internal pure { require(target != zero(), "Soullib: target is Zero address"); } ///@dev Sets new token address function resetTokenAddr(address newToken) public returns(bool) { //Perform check token = newToken; return true; } /**@dev Soulliber can enquire for callIds of specific index @param index - Position of soullibee in the list of soulliber's callers */ function getCallId(uint64 index) public view isASoulliber(_msgSender()) returns(uint) { uint len = profs[_msgSender()].callIds.length; //Perform check return profs[_msgSender()].callIds[index-1]; } ///@dev Internal: returns zero address function zero() internal pure returns(address) { return address(0); } /**@dev View only: Returns target's Category and MemberType e.g Categ.INDIV, and Share.SOULLIBEE */ function getUserCategory(address target) public view returns (Categ) { return (profs[target].cat); } /**@dev Public: signs up the caller as a soulliber @param referee - optional: Caller can either parse "referee" or not This is an address that referred the caller. Note: Caller cannot add themselves as the referee Caller must not have signed up before now */ function individualSoulliberSignUp(address referee) public whenNotPaused isNotSoulliber(_msgSender()) returns (bool) { if (referee == zero()) { referee = router; } //Perform check profs[_msgSender()].referee = referee; profs[_msgSender()].status[Share.SOULLIBER] = true; _complete(Categ.INDIV, _msgSender(), zero(), Share(1)); return true; } ///@dev Completes signup for "target" function _complete( Categ cat, address target, address upline, Share sh) internal { profs[target].cat = Categ(cat); _setStatus(target, Share.SOULLIBER, true); profs[target].sh = sh; uint256 count = counter[uint8(Categ(cat))]; counter[uint8(Categ(cat))] = count + 1; emit SignedUp(target, upline); } ///@dev Returns true if @param target is soulliber and false if otherwise function isSoulliber(address target) public view returns (bool) { return profs[target].status[Share.SOULLIBER]; } ///@dev Returns true if @param target is soullibee and false if otherwise function isSoullibee(address target) public view returns (bool) { return profs[target].status[Share.SOULLIBEE]; } /**@dev Private or Governmental organizations can sign up as a @param newAddress as soulliber to their profile @param _choseCategory - Position index in the category caller belongs to Note: _choseCategory should be either 1 or 2 1 ==> Private organization. 2 ==> Government. NOTE: _cat can only be between 0 and 3 but exclude 0. This because the default category "INDIV" cannot be upgraded to. */ function addASoulliberToProfile(uint8 _choseCategory, address newAddress) public whenNotPaused oneOrTwo(_choseCategory) isNotSoulliber(newAddress) returns (bool) { //Perform check //Set upline _setStatus(newAddress, Share.SOULLIBER, true); _setStatus(_msgSender(), Share.UPLINE, true); _complete(Categ(_choseCategory), newAddress, _msgSender(), Share(1)); return true; } /**@dev Anyone is able to sign up as a Soullibee Note: Anyone must not already have signed up before now */ function signUpAsSoullibee() public returns (bool) { //Perform check _setStatus(_msgSender(), Share.SOULLIBEE, true); return true; } /**@dev Caller is able tp pop out "soulliber" from profile NOTE: Only the upline can remove soulliber from account and they must have already been added before now */ function removeSoulliberFromProfile(address soulliber) public whenNotPaused isASoulliber(soulliber) returns (bool) { _notZero(soulliber); address upLine = profs[soulliber].upline; //Perform check Categ cat = profs[soulliber].cat; delete profs[soulliber]; emit Deleted(upLine, soulliber); return true; } /**@dev Anyone can remove themselves as a soullibee. Note: Cafeful should be taken as Anyone deleted themselves can no longer route a call */ function deleteAccountSoullibee() public returns (bool) { //Perform check delete profs[_msgSender()]; return true; } /**@dev This is triggered anytime a call is routed to the soulliber @param to - Soulliber address/Call receiver @param amount - Fee charged to soullibee for this call @param cat - category call receiver belongs to. @param ref - referee address if any NOTE: Referee can claim reward instantly. if "to" i.e call receiver does not have a referee, then they must have an upline If current time equals the set withdrawal window, then we move the balance in the withdrawable balance to the unclaimed ledge, swapped with the queuing gross balance accumulated for the past {withdrawal window} period. Any unclaimed balance is cleared and updated with current. */ function _receiveFeeUpdate( address to, uint256 amount, Categ cat, address ref) private { uint256[7] memory _rates = rates[cat]; rev.totalFeeGeneratedForARound += amount; rev.shares[ref] += amount.mul(_rates[6]).div(100); address upline = profs[to].upline; rev.shares[upline] += amount.mul(_rates[3]); rev.shares[to] += amount.mul(_rates[1]).div(100); rev.shares[address(this)] += amount.mul(_rates[2]).div(100); uint64 round = rev.round; rev.revenue[cat][round + 1] += amount; uint lud = rev.revenue[cat][3]; if(_now() >= lud.add(rev.withdrawWindow)) { uint p = rev.revenue[cat][round + 1]; uint p1 = rev.revenue[cat][round]; uint p2 = rev.revenue[cat][round + 2]; rev.revenue[cat][round + 1] = 0; (rev.revenue[cat][round], rev.revenue[cat][round + 2]) = (p2, p + p1); rev.revenue[cat][3] = SafeCast.toUint64(_now()); (rev.revenue[cat][revenueCounter], rev.totalFeeGeneratedForARound) = (rev.totalFeeGeneratedForARound, p); rev.boardShare = p.mul(_rates[4]).div(100).div(boardCount); revenueCounter ++; } if (rev.lastUnlockedDate == 0) { rev.lastUnlockedDate = SafeCast.toUint64(_now()); } } /**@dev Sets @param newwindow : Period which Staker and board member can claim withdrawal Note: "newWindow should be in days e.g 2 or 10 or any */ function setWithdrawWindow(uint16 newWindow) public onlyOwner returns(bool) { //Perform check rev.withdrawWindow = newWindow * 1 days; return true; } /** @dev View: Returns past generated fee @param round - Past revenueCounter: must not be less than 3 and should be less than or equal to current counter @param categoryIndex: From Categ(0, or 1, or 2) */ function getPastGeneratedFee(uint64 round, uint8 categoryIndex) public view lessThan3(categoryIndex) returns(uint) { uint cnt = revenueCounter; //Perform check return rev.revenue[Categ(categoryIndex)][round]; } ///@dev View: returns call charge , last unlocked date and current total fee generated function getFeeLastUnlockedFeeGeneratedForARound() public view returns (uint, uint, uint) { return (rev.perCallCharge, rev.lastUnlockedDate, rev.totalFeeGeneratedForARound); } /**@dev View: returns Gross generated fee for the @param categoryIndex : Position of the category enquiring for i.e INDIV or PRIV or GOVT NOTE: categoryIndex must not be greater than 3 i.e should be from 0 to 2 */ function getGrossGeneratedFee(uint8 categoryIndex) public view lessThan3(categoryIndex) returns (uint) { return rev.revenue[Categ(categoryIndex)][rev.round]; } /**@dev View: returns Claimable generated fee for the @param categoryIndex : Position of the category enquiring for i.e INDIV or PRIV or GOVT NOTE: categoryIndex must not be greater than 3 i.e should be from 0 to 2 */ function getClaimableGeneratedFee(uint8 categoryIndex) public view lessThan3(categoryIndex) returns (uint) { return rev.revenue[Categ(categoryIndex)][rev.round]; } /**@dev View: returns unclaimed generated fee for the @param categoryIndex : Position of the category enquiring for i.e INDIV or PRIV or GOVT NOTE: categoryIndex must not be greater than 3 i.e should be from 0 to 2 */ function getUnclaimedFee(uint8 categoryIndex) public view onlyAdmin lessThan3(categoryIndex) returns (uint) { return rev.revenue[Categ(categoryIndex)][rev.round + 1]; } /**@dev View: returns last time generated fee for "categoryIndex" for released for distribution @param categoryIndex : Position of the category enquiring for i.e INDIV or PRIV or GOVT NOTE: categoryIndex must not be greater than 3 i.e should be from 0 to 2 */ function getLastFeeReleasedDate(uint8 categoryIndex) public view onlyAdmin lessThan3(categoryIndex) returns (uint) { return rev.revenue[Categ(categoryIndex)][2]; } ///@dev View: Returns current block Unix time stamp function _now() internal view returns (uint256) { return block.timestamp; } function _getStatus(address target) internal view returns(bool, bool, bool, bool, bool, bool) { return ( profs[target].status[Share(0)], profs[target].status[Share(1)], profs[target].status[Share(2)], profs[target].status[Share(6)], profs[target].status[Share(5)], profs[target].status[Share(4)] ); } /**@notice Users in the Categ can claim fee reward if they're eligible Note: Referees are extempted */ function claimRewardExemptReferee() public whenNotPaused returns (bool) { (, bool isSouliber, bool isUplin,, bool isStaker, bool isBoard) = _getStatus(_msgSender()); // require(!isSolibee && !isRef, "Ref: Use designated method"); uint256 shr; if (isSouliber || isUplin) { shr = rev.shares[_msgSender()]; rev.shares[_msgSender()] = 0; } else { //Perform check //Perform check profs[_msgSender()].lastClaimedDate = SafeCast.toUint64(rev.lastUnlockedDate); uint256 lastBalChanged = profs[_msgSender()].lastBalChanged; (uint stak, uint bor) = _getThresholds(); //Perform check Categ cat = profs[_msgSender()].cat; shr = isStaker ? rev.stakersShare : rev.boardShare; rev.revenue[cat][rev.round + 2] -= shr; } //Perform check SafeBEP20.safeTransfer(IERC20(token), _msgSender(), shr); emit Claimed(_msgSender(), shr); return true; } ///@dev Only referee can claim using this method function claimReferralReward() public returns (bool) { (,,, bool isRef,,) = _getStatus(_msgSender()); //Perform check uint256 claim = rev.shares[_msgSender()]; //Perform check rev.shares[_msgSender()] = 0; _setStatus(_msgSender(), Share.REFEREE, false); SafeBEP20.safeTransfer(IERC20(token), _msgSender(), claim); emit Claimed(_msgSender(), claim); return true; } /**@dev Move unclaimed reward to "to" @param to - address to receive balance @param index - Which of the unclaimed pool balance from the Category do you want to move? Note: Callable only by the owner */ function moveUnclaimedReward(address to, uint8 index) public onlyowner lessThan3(index) returns (bool) { uint256 unclaimed = rev.revenue[Categ(index)][rev.round + 2]; //Perform check rev.revenue[Categ(index)][rev.round + 2] = 0; address[2] memory _to = [to, router]; uint sP; for(uint8 i = 0; i < _to.length; i++) { sP = unclaimed.mul(30).div(100); address to_ = _to[i]; if(to_ == to) { sP = unclaimed.mul(70).div(100); } SafeBEP20.safeTransfer(IERC20(token), to_, sP); } return true; } ///@dev View: Returbs the minimum stake for both staker and board members function _getThresholds() internal view returns (uint256, uint256) { return (thresholds[1], thresholds[2]); } ///@dev Internal: updates target's PROFILE status function _updateState( address target, uint8 cmd) internal returns (bool) { (uint256 staker, uint256 board) = _getThresholds(); uint256 lastBalChanged = profs[target].lastBalChanged; uint curStake = _stakes(target); if(cmd == 0) { if(curStake >= board) { _setStatus(target, Share.BOARD, true); } else if(curStake < board && curStake >= staker) { _setStatus(target, Share.STAKER, true); } else { _setStatus(target, Share.STAKER, false); } if(lastBalChanged == 0) { profs[target].lastBalChanged = _now(); } } else { profs[target].lastBalChanged = _now(); _setStatus(target, Share.STAKER, false); } return true; } /**@notice Utility to stake SLIB Token Note: Must not be disabled Staker's stake balance are tracked hence if an user unstake before the unlocked date, they will lose the reward. They must keep the stake up to a minimum of 30 days */ function stakeSlib(uint256 amount) public whenNotPaused returns (bool) { (uint stak, uint bor) = _getThresholds(); if(!hasStake(_msgSender())) { if(amount >= bor) { boardCount ++; } if(amount >= stak && amount < bor){ stakersCount ++; } } (bool thisSuccess, ) = token.call(abi.encodeWithSelector(TOGGLE_SELECTOR, _msgSender(), amount, 0)); //Perform check profs[_msgSender()].stake = _stakes(_msgSender()).add(amount); _updateState(_msgSender(), 0); emit Staked(_msgSender(), amount); return true; } /**@notice Utility for to unstake SLIB Token Note: Must not be disabled Staker's stake balance are tracked hence if an user unstake before the unlocked date, they will lose the reward. They must keep the stake up to a minimum of 30 days */ function unstakeSlib() public whenNotPaused returns (bool) { uint256 curStake = _stakes(_msgSender()); //Perform check profs[_msgSender()].stake = 0; (bool thisSuccess, ) = token.call(abi.encodeWithSelector(TOGGLE_SELECTOR, _msgSender(), curStake, 1)); //Perform check _updateState(_msgSender(), 1); emit Unstaked(_msgSender(), curStake); return true; } //@dev shows if target has stake running or not function hasStake(address target) public view returns (bool) { return _stakes(target) > 0; } ///@dev Internal: Returns stake position of @param target function _stakes(address target) internal view returns (uint256) { return profs[target].stake; } ///@dev Public: Returns stake position of @param target function stakes(address target) public view returns (uint256) { return _stakes(target); } /**@param to - Soullibee routes a call to a specific Soulliber @param "to" Performs a safe external low level calls to feeDistributor address */ function routACall(address to) public whenNotPaused isASoulliber(to) returns (bool) { //Perform check uint256 _fee = rev.perCallCharge; address ref = profs[to].referee; uint curId = rev.id; rev.id = curId + 1; profs[to].callIds.push(curId); (bool thisSuccess, ) = token.call(abi.encodeWithSelector(TOGGLE_SELECTOR, _msgSender(), _fee, 2)); //Perform check Categ ofClient = profs[to].cat; _setStatus(to, Share.REFEREE, true); _receiveFeeUpdate(to, _fee, ofClient, ref); emit CallSent(to, _msgSender()); return true; } ///@dev Internal : Sets @param target 's status to true function _setStatus(address target, Share sh, bool stat) internal { profs[target].status[sh] = stat; } ///@dev sets new fee on calls. function updateCallCharge(uint256 newPerCallCharge) public onlyAdmin { rev.perCallCharge = newPerCallCharge; } /**@dev sets minimum hold in SLIB for eitherstakers */ function setMinimumHoldForStaker(uint256 amount) public onlyAdmin { thresholds[1] = amount; } /**@dev sets minimum hold in SLIB for either board */ function setMinimumHoldForBoard(uint256 amount) public onlyAdmin { thresholds[2] = amount; } /**@dev sets minimum hold in SLIB for either board or stakers */ function getMinimumHolds() public view returns (uint256, uint256) { return (thresholds[1], thresholds[2]); } ///@notice Returns the total number of members in each "catIndex" function getCounterOfEachCategory(uint8 categoryIndex) public view onlyAdmin lessThan3(categoryIndex) returns (uint256) { return counter[categoryIndex]; } ///@notice Read only: returns rate for each subcategory in each category function getRate(uint8 categoryIndex) public view lessThan3(categoryIndex) returns (uint256[7] memory) { return rates[Categ(categoryIndex)]; } ///@dev Emergency withdraw function: Only owner is permitted function emergencyWithdraw(address to, uint256 amount) public onlyOwner returns (bool) { _notZero(to); //Perform check (bool success, ) = to.call{ value: amount }(""); //Perform check return true; } ///@dev Returns current withdrawal window function getWIthdrawalWindow() public view returns(uint96) { return rev.withdrawWindow; } }
View: Returns current block Unix time stamp
function _now() internal view returns (uint256) { return block.timestamp; }
12,722,085
pragma solidity 0.4.18; // File: contracts/ERC20Interface.sol // https://github.com/ethereum/EIPs/issues/20 interface ERC20 { function totalSupply() public view returns (uint supply); function balanceOf(address _owner) public view returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint remaining); function decimals() public view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } // File: contracts/PermissionGroups.sol contract PermissionGroups { address public admin; address public pendingAdmin; mapping(address=>bool) internal operators; mapping(address=>bool) internal alerters; address[] internal operatorsGroup; address[] internal alertersGroup; uint constant internal MAX_GROUP_SIZE = 50; function PermissionGroups() public { admin = msg.sender; } modifier onlyAdmin() { require(msg.sender == admin); _; } modifier onlyOperator() { require(operators[msg.sender]); _; } modifier onlyAlerter() { require(alerters[msg.sender]); _; } function getOperators () external view returns(address[]) { return operatorsGroup; } function getAlerters () external view returns(address[]) { return alertersGroup; } event TransferAdminPending(address pendingAdmin); /** * @dev Allows the current admin to set the pendingAdmin address. * @param newAdmin The address to transfer ownership to. */ function transferAdmin(address newAdmin) public onlyAdmin { require(newAdmin != address(0)); TransferAdminPending(pendingAdmin); pendingAdmin = newAdmin; } /** * @dev Allows the current admin to set the admin in one tx. Useful initial deployment. * @param newAdmin The address to transfer ownership to. */ function transferAdminQuickly(address newAdmin) public onlyAdmin { require(newAdmin != address(0)); TransferAdminPending(newAdmin); AdminClaimed(newAdmin, admin); admin = newAdmin; } event AdminClaimed( address newAdmin, address previousAdmin); /** * @dev Allows the pendingAdmin address to finalize the change admin process. */ function claimAdmin() public { require(pendingAdmin == msg.sender); AdminClaimed(pendingAdmin, admin); admin = pendingAdmin; pendingAdmin = address(0); } event AlerterAdded (address newAlerter, bool isAdd); function addAlerter(address newAlerter) public onlyAdmin { require(!alerters[newAlerter]); // prevent duplicates. require(alertersGroup.length < MAX_GROUP_SIZE); AlerterAdded(newAlerter, true); alerters[newAlerter] = true; alertersGroup.push(newAlerter); } function removeAlerter (address alerter) public onlyAdmin { require(alerters[alerter]); alerters[alerter] = false; for (uint i = 0; i < alertersGroup.length; ++i) { if (alertersGroup[i] == alerter) { alertersGroup[i] = alertersGroup[alertersGroup.length - 1]; alertersGroup.length--; AlerterAdded(alerter, false); break; } } } event OperatorAdded(address newOperator, bool isAdd); function addOperator(address newOperator) public onlyAdmin { require(!operators[newOperator]); // prevent duplicates. require(operatorsGroup.length < MAX_GROUP_SIZE); OperatorAdded(newOperator, true); operators[newOperator] = true; operatorsGroup.push(newOperator); } function removeOperator (address operator) public onlyAdmin { require(operators[operator]); operators[operator] = false; for (uint i = 0; i < operatorsGroup.length; ++i) { if (operatorsGroup[i] == operator) { operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1]; operatorsGroup.length -= 1; OperatorAdded(operator, false); break; } } } } // File: contracts/Withdrawable.sol /** * @title Contracts that should be able to recover tokens or ethers * @author Ilan Doron * @dev This allows to recover any tokens or Ethers received in a contract. * This will prevent any accidental loss of tokens. */ contract Withdrawable is PermissionGroups { event TokenWithdraw(ERC20 token, uint amount, address sendTo); /** * @dev Withdraw all ERC20 compatible tokens * @param token ERC20 The address of the token contract */ function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin { require(token.transfer(sendTo, amount)); TokenWithdraw(token, amount, sendTo); } event EtherWithdraw(uint amount, address sendTo); /** * @dev Withdraw Ethers */ function withdrawEther(uint amount, address sendTo) external onlyAdmin { sendTo.transfer(amount); EtherWithdraw(amount, sendTo); } } // File: contracts/KyberReserveInterface.sol /// @title Kyber Reserve contract interface KyberReserveInterface { function trade( ERC20 srcToken, uint srcAmount, ERC20 destToken, address destAddress, uint conversionRate, bool validate ) public payable returns(bool); function getConversionRate(ERC20 src, ERC20 dest, uint srcQty, uint blockNumber) public view returns(uint); } // File: contracts/Utils.sol /// @title Kyber constants contract contract Utils { ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); uint constant internal PRECISION = (10**18); uint constant internal MAX_QTY = (10**28); // 10B tokens uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH uint constant internal MAX_DECIMALS = 18; uint constant internal ETH_DECIMALS = 18; mapping(address=>uint) internal decimals; function setDecimals(ERC20 token) internal { if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS; else decimals[token] = token.decimals(); } function getDecimals(ERC20 token) internal view returns(uint) { if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access uint tokenDecimals = decimals[token]; // technically, there might be token with decimals 0 // moreover, very possible that old tokens have decimals 0 // these tokens will just have higher gas fees. if(tokenDecimals == 0) return token.decimals(); return tokenDecimals; } function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(srcQty <= MAX_QTY); require(rate <= MAX_RATE); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION; } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals))); } } function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(dstQty <= MAX_QTY); require(rate <= MAX_RATE); //source quantity is rounded up. to avoid dest quantity being too low. uint numerator; uint denominator; if (srcDecimals >= dstDecimals) { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals))); denominator = rate; } else { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty); denominator = (rate * (10**(dstDecimals - srcDecimals))); } return (numerator + denominator - 1) / denominator; //avoid rounding down errors } } // File: contracts/Utils2.sol contract Utils2 is Utils { /// @dev get the balance of a user. /// @param token The token type /// @return The balance function getBalance(ERC20 token, address user) public view returns(uint) { if (token == ETH_TOKEN_ADDRESS) return user.balance; else return token.balanceOf(user); } function getDecimalsSafe(ERC20 token) internal returns(uint) { if (decimals[token] == 0) { setDecimals(token); } return decimals[token]; } function calcDestAmount(ERC20 src, ERC20 dest, uint srcAmount, uint rate) internal view returns(uint) { return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate); } function calcSrcAmount(ERC20 src, ERC20 dest, uint destAmount, uint rate) internal view returns(uint) { return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate); } function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint dstDecimals) internal pure returns(uint) { require(srcAmount <= MAX_QTY); require(destAmount <= MAX_QTY); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount)); } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount); } } } // File: contracts/uniswap/UniswapReserve.sol interface UniswapExchange { function getEthToTokenInputPrice( uint256 eth_sold ) external view returns (uint256 tokens_bought); function getTokenToEthInputPrice( uint256 tokens_sold ) external view returns (uint256 eth_bought); function ethToTokenSwapInput( uint256 min_tokens, uint256 deadline ) external payable returns (uint256 tokens_bought); function tokenToEthSwapInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline ) external returns (uint256 eth_bought); } interface UniswapFactory { function getExchange(address token) external view returns (address exchange); } contract UniswapReserve is KyberReserveInterface, Withdrawable, Utils2 { // Parts per 10000 uint public constant DEFAULT_FEE_BPS = 25; UniswapFactory public uniswapFactory; address public kyberNetwork; uint public feeBps = DEFAULT_FEE_BPS; // Uniswap exchange contract for every listed token // token -> exchange mapping (address => address) public tokenExchange; bool public tradeEnabled = true; /** Constructor */ function UniswapReserve( UniswapFactory _uniswapFactory, address _admin, address _kyberNetwork ) public { require(address(_uniswapFactory) != 0); require(_admin != 0); require(_kyberNetwork != 0); uniswapFactory = _uniswapFactory; admin = _admin; kyberNetwork = _kyberNetwork; } function() public payable { // anyone can deposit ether } /** Returns dest quantity / source quantity. */ function getConversionRate( ERC20 src, ERC20 dest, uint srcQty, uint blockNumber ) public view returns(uint) { // This makes the UNUSED warning go away. blockNumber; require(isValidTokens(src, dest)); if (!tradeEnabled) return 0; ERC20 token; if (src == ETH_TOKEN_ADDRESS) { token = dest; } else if (dest == ETH_TOKEN_ADDRESS) { token = src; } else { // Should never arrive here - isValidTokens requires one side to be ETH revert; } UniswapExchange exchange = UniswapExchange( uniswapFactory.getExchange(token) ); uint convertedQuantity; if (src == ETH_TOKEN_ADDRESS) { uint quantity = srcQty * (10000 - feeBps) / 10000; convertedQuantity = exchange.getEthToTokenInputPrice(quantity); } else { convertedQuantity = exchange.getTokenToEthInputPrice(srcQty); convertedQuantity = convertedQuantity * (10000 - feeBps) / 10000; } return calcRateFromQty( srcQty, /* srcAmount */ convertedQuantity, /* destAmount */ getDecimals(src), /* srcDecimals */ getDecimals(dest) /* dstDecimals */ ); } event TradeExecute( address indexed sender, address src, uint srcAmount, address destToken, uint destAmount, address destAddress ); /** conversionRate: expected conversion rate should be >= this value. */ function trade( ERC20 srcToken, uint srcAmount, ERC20 destToken, address destAddress, uint conversionRate, bool validate ) public payable returns(bool) { require(tradeEnabled); require(msg.sender == kyberNetwork); require(isValidTokens(srcToken, destToken)); uint expectedConversionRate = getConversionRate( srcToken, destToken, srcAmount, 0 /* blockNumber */ ); require (expectedConversionRate <= conversionRate); uint destAmount; UniswapExchange exchange; if (srcToken == ETH_TOKEN_ADDRESS) { require(srcAmount == msg.value); // Fees in ETH uint quantity = srcAmount * (10000 - feeBps) / 10000; exchange = UniswapExchange(tokenExchange[destToken]); destAmount = exchange.ethToTokenSwapInput.value(quantity)( 0, 2 ** 255 /* deadline */ ); require(destToken.transfer(destAddress, destAmount)); } else { require(msg.value == 0); require(srcToken.transferFrom(msg.sender, address(this), srcAmount)); exchange = UniswapExchange(tokenExchange[srcToken]); destAmount = exchange.tokenToEthSwapInput( srcAmount, 0, 2 ** 255 /* deadline */ ); // Fees in ETH destAmount = destAmount * (10000 - feeBps) / 10000; destAddress.transfer(destAmount); } TradeExecute( msg.sender /* sender */, srcToken /* src */, srcAmount /* srcAmount */, destToken /* destToken */, destAmount /* destAmount */, destAddress /* destAddress */ ); return true; } event FeeUpdated( uint bps ); function setFee( uint bps ) public onlyAdmin { require(bps <= 10000); feeBps = bps; FeeUpdated(bps); } event TokenListed( ERC20 token, UniswapExchange exchange ); function listToken(ERC20 token) public onlyAdmin { require(address(token) != 0); UniswapExchange uniswapExchange = UniswapExchange( uniswapFactory.getExchange(token) ); tokenExchange[token] = uniswapExchange; setDecimals(token); require(token.approve(uniswapExchange, 2**255)); TokenListed(token, uniswapExchange); } event TokenDelisted(ERC20 token); function delistToken(ERC20 token) public onlyAdmin { require(tokenExchange[token] != 0); tokenExchange[token] = 0; TokenDelisted(token); } function isValidTokens( ERC20 src, ERC20 dest ) public view returns(bool) { return ( (src == ETH_TOKEN_ADDRESS && tokenExchange[dest] != 0) || (tokenExchange[src] != 0 && dest == ETH_TOKEN_ADDRESS) ); } event TradeEnabled( bool enable ); function enableTrade() public onlyAdmin returns(bool) { tradeEnabled = true; TradeEnabled(true); return true; } function disableTrade() public onlyAlerter returns(bool) { tradeEnabled = false; TradeEnabled(false); return true; } }
/ Fees in ETH Fees in ETH
function trade( ERC20 srcToken, uint srcAmount, ERC20 destToken, address destAddress, uint conversionRate, bool validate ) public payable returns(bool) { require(tradeEnabled); require(msg.sender == kyberNetwork); require(isValidTokens(srcToken, destToken)); uint expectedConversionRate = getConversionRate( srcToken, destToken, srcAmount, 0 /* blockNumber */ ); require (expectedConversionRate <= conversionRate); uint destAmount; UniswapExchange exchange; if (srcToken == ETH_TOKEN_ADDRESS) { require(srcAmount == msg.value); uint quantity = srcAmount * (10000 - feeBps) / 10000; exchange = UniswapExchange(tokenExchange[destToken]); destAmount = exchange.ethToTokenSwapInput.value(quantity)( 0, 2 ** 255 /* deadline */ ); require(destToken.transfer(destAddress, destAmount)); require(msg.value == 0); require(srcToken.transferFrom(msg.sender, address(this), srcAmount)); exchange = UniswapExchange(tokenExchange[srcToken]); destAmount = exchange.tokenToEthSwapInput( srcAmount, 0, 2 ** 255 /* deadline */ ); destAmount = destAmount * (10000 - feeBps) / 10000; destAddress.transfer(destAmount); } TradeExecute( msg.sender /* sender */, srcToken /* src */, srcAmount /* srcAmount */, destToken /* destToken */, destAmount /* destAmount */, destAddress /* destAddress */ ); return true; } event FeeUpdated( uint bps );
5,454,566
//Address: 0x76645F7C6F98caD248474e9a38D4A38c4173F2a4 //Contract name: POTENTIAM //Balance: 0 Ether //Verification Date: 2/9/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @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 { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, Pausable { using SafeMath for uint256; uint256 public etherRaised; mapping(address => uint256) balances; address companyReserve; uint256 deployTime; modifier isUserAbleToTransferCheck(uint256 _value) { if(msg.sender == companyReserve){ uint256 balanceRemaining = balanceOf(companyReserve); uint256 timeDiff = now - deployTime; uint256 totalMonths = timeDiff / 30 days; if(totalMonths == 0){ totalMonths = 1; } uint256 percentToWitdraw = totalMonths * 5; uint256 tokensToWithdraw = ((25000000 * (10**18)) * percentToWitdraw)/100; uint256 spentTokens = (25000000 * (10**18)) - balanceRemaining; if(spentTokens + _value <= tokensToWithdraw){ _; } else{ revert(); } }else{ _; } } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public isUserAbleToTransferCheck(_value) returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BurnableToken is BasicToken { using SafeMath for uint256; event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply= totalSupply.sub(_value); Burn(burner, _value); } } contract StandardToken is ERC20, BurnableToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public isUserAbleToTransferCheck(_value) returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract POTENTIAM is StandardToken, Destructible { string public constant name = "POTENTIAM"; using SafeMath for uint256; uint public constant decimals = 18; string public constant symbol = "PTM"; uint public priceOfToken=250000000000000;//1 eth = 4000 PTM address[] allParticipants; uint tokenSales=0; uint256 public firstWeekPreICOBonusEstimate; uint256 public secondWeekPreICOBonusEstimate; uint256 public firstWeekMainICOBonusEstimate; uint256 public secondWeekMainICOBonusEstimate; uint256 public thirdWeekMainICOBonusEstimate; uint256 public forthWeekMainICOBonusEstimate; uint256 public firstWeekPreICOBonusRate; uint256 secondWeekPreICOBonusRate; uint256 firstWeekMainICOBonusRate; uint256 secondWeekMainICOBonusRate; uint256 thirdWeekMainICOBonusRate; uint256 forthWeekMainICOBonusRate; uint256 totalWeiRaised = 0; function POTENTIAM() public { totalSupply = 100000000 * (10**decimals); // owner = msg.sender; companyReserve = 0xd311cB7D961B46428d766df0eaE7FE83Fc8B7B5c;//TODO change address balances[msg.sender] += 75000000 * (10 **decimals); balances[companyReserve] += 25000000 * (10**decimals); firstWeekPreICOBonusEstimate = now + 7 days; deployTime = firstWeekPreICOBonusEstimate; secondWeekPreICOBonusEstimate = firstWeekPreICOBonusEstimate + 7 days; firstWeekMainICOBonusEstimate = firstWeekPreICOBonusEstimate + 14 days; secondWeekMainICOBonusEstimate = firstWeekPreICOBonusEstimate + 21 days; thirdWeekMainICOBonusEstimate = firstWeekPreICOBonusEstimate + 28 days; forthWeekMainICOBonusEstimate = firstWeekPreICOBonusEstimate + 35 days; firstWeekPreICOBonusRate = 20; secondWeekPreICOBonusRate = 18; firstWeekMainICOBonusRate = 12; secondWeekMainICOBonusRate = 8; thirdWeekMainICOBonusRate = 4; forthWeekMainICOBonusRate = 0; } function() public whenNotPaused payable { require(msg.value>0); require(now<=forthWeekMainICOBonusEstimate); require(tokenSales < (60000000 * (10 **decimals))); uint256 bonus = 0; if(now<=firstWeekPreICOBonusEstimate && totalWeiRaised < 5000 wei){ bonus = firstWeekPreICOBonusRate; }else if(now <=secondWeekPreICOBonusEstimate && totalWeiRaised < 6000 wei){ bonus = secondWeekPreICOBonusRate; }else if(now<=firstWeekMainICOBonusEstimate && totalWeiRaised < 9000){ bonus = firstWeekMainICOBonusRate; }else if(now<=secondWeekMainICOBonusEstimate && totalWeiRaised < 12000){ bonus = secondWeekMainICOBonusRate; } else if(now<=thirdWeekMainICOBonusEstimate && totalWeiRaised <14000){ bonus = thirdWeekMainICOBonusRate; } uint256 tokens = (msg.value * (10 ** decimals)) / priceOfToken; uint256 bonusTokens = ((tokens * bonus) /100); tokens +=bonusTokens; if(balances[owner] <tokens) //check etiher owner can have token otherwise reject transaction and ether { revert(); } allowed[owner][msg.sender] += tokens; bool transferRes=transferFrom(owner, msg.sender, tokens); if (!transferRes) { revert(); } else{ tokenSales += tokens; etherRaised += msg.value; } }//end of fallback /** * Transfer entire balance to any account (by owner and admin only) **/ function transferFundToAccount(address _accountByOwner) public onlyOwner { require(etherRaised > 0); _accountByOwner.transfer(etherRaised); etherRaised = 0; } function resetTokenOfAddress(address _userAddr, uint256 _tokens) public onlyOwner returns (uint256){ require(_userAddr !=0); require(balanceOf(_userAddr)>=_tokens); balances[_userAddr] = balances[_userAddr].sub(_tokens); balances[owner] = balances[owner].add(_tokens); return balances[_userAddr]; } /** * Transfer part of balance to any account (by owner and admin only) **/ function transferLimitedFundToAccount(address _accountByOwner, uint256 balanceToTransfer) public onlyOwner { require(etherRaised > balanceToTransfer); _accountByOwner.transfer(balanceToTransfer); etherRaised -= balanceToTransfer; } }
Burns a specific amount of tokens. _value The amount of token to be burned./ no need to require value <= totalSupply, since that would imply the sender's balance is greater than the totalSupply, which should be an assertion failure
function burn(uint256 _value) public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply= totalSupply.sub(_value); Burn(burner, _value); }
12,872,365
pragma solidity ^0.6.0; /** * @title Primitive's Pool Contract * @notice The pool contract. * @author Primitive */ /** * @title Primitive's Instruments * @author Primitive Finance */ library Instruments { /** * @dev A Prime has these properties. * @param ace `msg.sender` of the createPrime function. * @param xis Quantity of collateral asset token. * @param yak Address of collateral asset token. * @param zed Purchase price of collateral, denominated in quantity of token z. * @param wax Address of purchase price asset token. * @param pow UNIX timestamp of valid time period. * @param gem Address of payment receiver of token z. */ struct Primes { address ace; uint256 xis; address yak; uint256 zed; address wax; uint256 pow; address gem; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal virtual { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // 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) external view 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; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ abstract contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public virtual returns (bytes4); } contract ERC721Holder is IERC721Receiver { function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of `from`'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of `from`'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @dev Optional functions from the ERC20 standard. */ abstract contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @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. * * 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; } } abstract contract IPrime { function createPrime(uint256 _xis, address _yak, uint256 _zed, address _wax, uint256 _pow, address _gem) external virtual returns (uint256 _tokenId); function exercise(uint256 _tokenId) external virtual returns (bool); function close(uint256 _collateralId, uint256 _burnId) external virtual returns (bool); function withdraw(uint256 _amount, address _asset) public virtual returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId) external virtual; function isGreaterThanOrEqual(uint256 _a, uint256 _b) public pure virtual returns(bool); } abstract contract ICEther { function mint() external payable virtual; function redeem(uint redeemTokens) external virtual returns (uint); function redeemUnderlying(uint redeemAmount) external virtual returns (uint); function transfer(address dst, uint amount) external virtual returns (bool); function transferFrom(address src, address dst, uint amount) external virtual returns (bool); function approve(address spender, uint amount) external virtual returns (bool); function allowance(address owner, address spender) external virtual view returns (uint); function balanceOf(address owner) external virtual view returns (uint); function balanceOfUnderlying(address owner) external virtual returns (uint); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); function borrowRatePerBlock() external virtual view returns (uint); function supplyRatePerBlock() external virtual view returns (uint); function totalBorrowsCurrent() external virtual returns (uint); function borrowBalanceCurrent(address account) external virtual returns (uint); function borrowBalanceStored(address account) public virtual view returns (uint); function _exchangeRateCurrent() public virtual returns (uint); function _exchangeRateStored() public virtual view returns (uint); function getCash() external virtual view returns (uint); function accrueInterest() public virtual returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external virtual returns (uint); } contract Pool is Ownable, Pausable, ReentrancyGuard, ERC721Holder, ERC20, ERC20Detailed { using SafeMath for uint256; /* Address of Prime ERC-721 */ address public _primeAddress; address public _compoundEthAddress; address public _exchangeAddress; ICEther public _cEther; IPrime public _prime; /* Ether liability */ uint256 public _liability; /* For testing */ uint256 public constant _premiumDenomination = 5; /* 20% = 0.2 = 1 / 5 */ event Debug(string error, uint256 result, uint256 tokenBalance); event Deposit(uint256 _deposit, address _user, uint256 _pulpMinted); event Withdraw(uint256 _withdraw, address _user, uint256 _pulpBurned); event PoolMint(uint256 _nonce, uint256 _collateralAmount, uint256 _strikeAmount); event Exercise(uint256 _amount, uint256 _strikeAmount); event Close(uint256 _closed, address _address, uint256 _pulpBurned); constructor ( address primeAddress, address compoundEthAddress, address exchangeAddress ) public ERC20Detailed( "Primitive Underlying Liquidity Provider", "PULP", 18 ) { _primeAddress = primeAddress; _exchangeAddress = exchangeAddress; _prime = IPrime(primeAddress); _cEther = ICEther(compoundEthAddress); _compoundEthAddress = compoundEthAddress; } /* SET*/ function setExchangeAddress(address exchangeAddress) external onlyOwner { _exchangeAddress = exchangeAddress; } receive() external payable {} /* CAPITAL INPUT / OUTPUT FUNCTIONS*/ /** * @dev deposits funds to the liquidity pool * @param _value amount of ether to deposit * @return bool true if liquidity tokens were minted and ether deposit swapped to cETher */ function deposit( uint256 _value ) external payable whenNotPaused returns (bool) { /* CHECKS */ require(msg.value == _value, 'Deposit: Val < deposit'); /* EFFECTS */ /* INTERACTIONS */ /* Mint Amount = Deposit / Total Ether In Pool / Total Supply of Liquidity Token */ uint256 totalSupply = totalSupply(); uint256 poolBalance = getPoolBalance(); uint256 amountToMint; if(poolBalance.mul(totalSupply) == 0) { amountToMint = _value; } else { amountToMint = _value.mul(totalSupply).div(poolBalance); } emit Deposit(_value, msg.sender, amountToMint); _mint(msg.sender, amountToMint); return swapEtherToCompoundEther(_value); } /** * @dev withdraw ether that is not utilized as collateral * @notice withdrawing utilized collateral requires the debt to be paid using the close function * @param _amount amount of ether to withdraw * @return bool true if liquidity tokens were burned, cEther was swapped to ether and sent */ function withdraw( uint256 _amount ) public nonReentrant returns (bool) { /* CHECKS */ require(balanceOf(msg.sender) >= _amount, 'Withdraw: Bal < withdraw'); require(getMaxBurnAmount() >= _amount, 'Withdraw: max burn < amt'); /* EFFECTS */ /* INTERACTIONS */ /* Burn PULP Tokens */ _burn(msg.sender, _amount); emit Withdraw(getEthWithdrawAmount(_amount), msg.sender, _amount); /* COMPOUND */ /* Redeem cTokens and send user Ether */ return swapCTokensToEtherThenSend(_amount, msg.sender); /* return sendEther(getEthWithdrawAmount(_amount), msg.sender); */ } /* GET BALANCE SHEET ITEMS */ /** * @dev get ether balance of contract * @return uint256 balance of contract in ether */ function getPoolBalance() public returns(uint256) { /* ET, where ET = Total Ether */ /* if(_cEther.balanceOf(address(this)) == 0) { return 0; } uint256 exchangeRate = _cEther._exchangeRateCurrent(); return _cEther.balanceOf(address(this)).mul(exchangeRate).div(10**28); */ return _cEther.balanceOfUnderlying(address(this)); /* return address(this).balance; */ } /** * @dev returns Net Assets = Pool Assets - Pool Liabilities * @return pool amount of available assets */ function getAvailableAssets() public returns (uint256) { /* Net Assets = ET - L, where ET = Total Ether and L = Total Liabilities */ uint256 poolBalance = getPoolBalance(); if(_liability > poolBalance) { return 0; } uint256 available = poolBalance.sub(_liability); return available; } /** * @dev returns Net Assets = Pool Assets - Pool Liabilities * @return pool returns 1 / Exchange Rate to use in LP token swaps */ function totalSupplyDivTotalEther() public returns (uint256) { /* Exchange rate = ET / ST, where ET = Total Ether balance, and ST = Total LP Supply */ if(totalSupply().mul(getPoolBalance()) == 0) { return 1; } return totalSupply().div(getPoolBalance()); } /** @dev tokens to burn to withdraw all non-utilized collateral @return uint256 max amount of tokens that can be burned for ether */ function getMaxBurnAmount() public returns (uint256) { /* LP = (ET - L) * ST / ET where ST = Total Supply */ uint256 maxBurn = getAvailableAssets().mul(totalSupply()).div(getPoolBalance()); require(getEthWithdrawAmount(maxBurn) <= getAvailableAssets(), 'Withdraw > net assets'); return maxBurn; } /** @dev returns the amount of ETH returned from swapped amount of Liquidity tokens */ function getEthWithdrawAmount(uint256 _amount) public returns (uint256) { /* LP = A * ET / ST, where LP = Primitive token, A = Amount, ET = Ether balance, ST = Total LP Supply */ if(totalSupply().mul(getPoolBalance()) == 0) { return _amount; } return _amount.mul(getPoolBalance()).div(totalSupply()); } /* PRIME INTERACTION FUNCTIONS */ /** * @dev user mints a Prime option from the pool * @param _long amount of ether (in wei) * @param _short amount of strike asset * @param _strike address of strike * @param _expiration timestamp of series expiration * @return bool whether or not the Prime is minted */ function mintPrimeFromPool( uint256 _long, uint256 _short, address _strike, uint256 _expiration, address payable _primeReceiver ) external payable whenNotPaused returns (bool) { /* CHECKS */ /* Checks to see if the tx pays the premium - 20% constant right now */ require(msg.value >= _long.div(_premiumDenomination), 'Mint: Val < premium'); require(_expiration > block.timestamp, 'Mint: expired'); require(getAvailableAssets() >= _long, 'Mint: available < amt'); /* EFFECTS */ /* Add the ether liability to the Pool */ _liability = _liability.add(_long); /* INTERACTIONS */ /* Mint a Prime */ uint256 nonce = _prime.createPrime( _long, address(this), _short, _strike, _expiration, address(this) ); /* Transfer Prime to User from Pool */ _prime.safeTransferFrom(address(this), _primeReceiver, nonce); emit PoolMint(nonce, _long, _short); /* COMPOUND */ /* Swap Pool ether to interest Bearing cEther */ return swapEtherToCompoundEther(msg.value); /* return true; */ } /** * @dev Called ONLY from the Prime contract * @param _long amount of collateral * @param _short amount of strike * @param _strike address of strike */ function exercise( uint256 _long, uint256 _short, address _strike ) external payable whenNotPaused returns (bool) { /* CHECKS */ /* This function should only be called by Prime */ require(msg.sender == _primeAddress); /* EFFECTS */ /* Clear liability of Prime */ _liability = _liability.sub(_long); /* INTERACTIONS */ /* COMPOUND */ /* Check if enough cTokens can be redeemed to meet collateral */ require(getPoolBalance() >= _long, 'Swap: ether < collat'); /* Swap cEther to Ether */ uint256 redeemResult = _cEther.redeemUnderlying(_long); require(redeemResult == 0, 'Swap: redeem != 0'); /* Sent to trusted address - Prime Contract */ sendEther(_long, msg.sender); emit Exercise(_long, _short); /* Withdraw strike assets from prime */ return _prime.withdraw(_short, _strike); } /** * @dev buy debt, withdraw capital * @notice user must purchase option and sell to pool, i.e. burn liability (Prime Token) */ function closePosition(uint256 _amount) external payable returns (bool) { /* CHECKS */ uint256 userEthBal = balanceOf(msg.sender); require(userEthBal >= _amount, 'Close: Eth Bal < amt'); uint256 poolBalance = getPoolBalance(); uint256 debt = _amount.mul(_liability).div(poolBalance); require(msg.value >= debt, 'Close: Value < debt'); /* EFFECTS */ uint256 refundEther = msg.value.sub(debt); /* INTERACTIONS */ _burn(msg.sender, _amount); emit Close(getEthWithdrawAmount(_amount.add(refundEther)), msg.sender, _amount); /* COMPOUND */ return swapCTokensToEtherThenSend(getEthWithdrawAmount(_amount.add(refundEther)), msg.sender); /* return sendEther(getEthWithdrawAmount(_amount).add(refundEther), msg.sender); */ } /* CAPITAL MANAGEMENT FUNCTIONS */ /** @dev function to send ether with the most security */ function sendEther(uint256 _amount, address payable _user) internal returns (bool) { (bool success, ) = _user.call.value(_amount)(""); require(success, "Send ether fail"); return success; } /* COMPOUND INTERFACE FUNCTIONS */ /** @dev converts ether to interest bearing cEther (Compound Protocol) @param _amount ether that will be swapped to cEther */ function swapEtherToCompoundEther(uint256 _amount) internal returns (bool) { _cEther.mint.value(_amount).gas(250000)(); return true; } /** @dev converts cEther back into Ether @param _amount ether that will be swapped to cEther */ function swapCTokensToEtherThenSend(uint256 _amount, address payable _user) internal returns (bool) { uint256 redeemResult = _cEther.redeemUnderlying(_amount); require(redeemResult == 0, 'redeem != 0'); (bool success, ) = _user.call.value(_amount)(""); require(success, 'Transfer fail.'); return success; /* uint256 redeemResult = _cEther.redeem(_amount); uint256 exchangeRate = _cEther._exchangeRateCurrent(); require(redeemResult == 0, 'redeem != 0'); (bool success, ) = _user.call.value(_amount.mul(exchangeRate).div(10**18))(""); require(success, 'Transfer fail.'); return success; */ } }
CHECKS / This function should only be called by Prime / EFFECTS / Clear liability of Prime / INTERACTIONS / COMPOUND / Check if enough cTokens can be redeemed to meet collateral / Swap cEther to Ether / Sent to trusted address - Prime Contract / Withdraw strike assets from prime / buy debt, withdraw capital user must purchase option and sell to pool, i.e. burn liability (Prime Token)/
function closePosition(uint256 _amount) external payable returns (bool) { uint256 userEthBal = balanceOf(msg.sender); require(userEthBal >= _amount, 'Close: Eth Bal < amt'); uint256 poolBalance = getPoolBalance(); uint256 debt = _amount.mul(_liability).div(poolBalance); require(msg.value >= debt, 'Close: Value < debt'); uint256 refundEther = msg.value.sub(debt); _burn(msg.sender, _amount); emit Close(getEthWithdrawAmount(_amount.add(refundEther)), msg.sender, _amount); return swapCTokensToEtherThenSend(getEthWithdrawAmount(_amount.add(refundEther)), msg.sender); }
14,077,692
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract JFToken is ERC20, Ownable { uint256 private constant preMineSupply = 20000000 * 1e18; using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private _minters; constructor() public ERC20("Jswap Finance Token", "JF"){ _mint(msg.sender, preMineSupply); } // mint with max supply function mint(address _to, uint256 _amount) public onlyMinter returns (bool) { _mint(_to, _amount); return true; } function addMinter(address _addMinter) public onlyOwner returns (bool) { require(_addMinter != address(0), "JfToken: _addMinter is the zero address"); return EnumerableSet.add(_minters, _addMinter); } function delMinter(address _delMinter) public onlyOwner returns (bool) { require(_delMinter != address(0), "JfToken: _delMinter is the zero address"); return EnumerableSet.remove(_minters, _delMinter); } function getMinterLength() public view returns (uint256) { return EnumerableSet.length(_minters); } function isMinter(address account) public view returns (bool) { return EnumerableSet.contains(_minters, account); } function getMinter(uint256 _index) public view onlyOwner returns (address){ require(_index <= getMinterLength() - 1, "JfToken: index out of bounds"); return EnumerableSet.at(_minters, _index); } // modifier for mint function modifier onlyMinter() { require(isMinter(msg.sender), "caller is not the minter"); _; } }
mint with max supply
function mint(address _to, uint256 _amount) public onlyMinter returns (bool) { _mint(_to, _amount); return true; }
2,549,598
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "./IERC20.sol"; import "./IERC20Sec.sol"; import "./IFreezable.sol"; import "./IBurnable.sol"; import "./IMintable.sol"; import "./AccessControl.sol"; import "./Pausable.sol"; import "./Wallet.sol"; /** * @dev Implementation of the {IERC20, IERC20Sec} interfaces. */ contract LivelyToken is IERC20, IERC20Sec, IFreezable, IBurnable, IMintable, AccessControl, Pausable, Wallet { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint256) private _freezes; uint256 private _totalSupply; /** * @dev error IllegalArgumentError */ error IllegalArgumentError(); /** * @dev error IllegalBalanceError */ error IllegalBalanceError(); /** * @dev error IllegalTotalSupplyError */ error IllegalTotalSupplyError(); /** * @dev error IllegalAllowanceError */ error IllegalAllowanceError(); /** * @dev error IllegalWalletAddressError */ error IllegalWalletAddressError(); /** * @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() { _totalSupply = 1_000_000_000 * 10**18; _balances[PUBLIC_SALE_WALLET_ADDRESS] = 500_000_000 * 10**18; // equivalent 50% total supply _balances[FOUNDING_TEAM_WALLET_ADDRESS] = 200_000_000 * 10**18; // equivalent 20% total supply _balances[RESERVES_WALLET_ADDRESS] = 100_000_000 * 10**18; // equivalent 10% total supply _balances[AUDIO_VIDEO_PRODUCTIONS_WALLET_ADDRESS] = 80_000_000 * 10**18; // equivalent 8% total supply _balances[BOUNTY_PROGRAMS_WALLET_ADDRESS] = 70_000_000 * 10**18; // equivalent 7% total supply _balances[CHARITY_WALLET_ADDRESS] = 50_000_000 * 10**18; // equivalent 5% total supply _allowances[PUBLIC_SALE_WALLET_ADDRESS][msg.sender] = 500_000_000 * 10**18; _allowances[AUDIO_VIDEO_PRODUCTIONS_WALLET_ADDRESS][msg.sender] = 80_000_000 * 10**18; _allowances[BOUNTY_PROGRAMS_WALLET_ADDRESS][msg.sender] = 70_000_000 * 10**18; _allowances[CHARITY_WALLET_ADDRESS][msg.sender] = 50_000_000 * 10**18; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, Pausable) returns (bool) { return interfaceId == type(IERC20).interfaceId || interfaceId == type(IERC20Sec).interfaceId || interfaceId == type(IBurnable).interfaceId || interfaceId == type(IMintable).interfaceId || interfaceId == type(IPausable).interfaceId || interfaceId == type(IFreezable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns the name of the token. */ function name() external pure override returns (string memory) { return "Lively"; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external pure override returns (string memory) { return "LVL"; } /** * @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() external pure override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() external view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } /** * @dev CONSENSUS_ROLE must initialize by ADMIN_ROLE only once * */ // solhint-disable-next-line function firstInitializeConsensusRole(address account) public validateSenderRole(ADMIN_ROLE) validateAddress(account) { _firstInitializeConsensusRole(account); _allowances[PUBLIC_SALE_WALLET_ADDRESS][account] = 500_000_000 * 10**18; _allowances[FOUNDING_TEAM_WALLET_ADDRESS][account] = 200_000_000 * 10**18; _allowances[RESERVES_WALLET_ADDRESS][account] = 100_000_000 * 10**18; _allowances[AUDIO_VIDEO_PRODUCTIONS_WALLET_ADDRESS][account] = 80_000_000 * 10**18; _allowances[BOUNTY_PROGRAMS_WALLET_ADDRESS][account] = 70_000_000 * 10**18; _allowances[CHARITY_WALLET_ADDRESS][account] = 50_000_000 * 10**18; } /** * @dev See {IFreezable-freezeOf}. */ // TODO test for address(0x0) function freezeOf(address account) external view override returns (uint256) { return _freezes[account]; } /** * @dev See {IFreezable-freeze}. */ function freeze(uint256 currentFreezeBalance, uint256 amount) external override whenNotPaused whenNotPausedOf(msg.sender) validateSenderAccount returns (uint256 newFreezeBalance) { newFreezeBalance = _freeze(msg.sender, currentFreezeBalance, amount); emit Freeze(msg.sender, currentFreezeBalance, amount); return newFreezeBalance; } /** * @dev See {IFreezable-unfreeze}. */ function unfreeze(uint256 currentFreezeBalance, uint256 amount) external override whenNotPaused whenNotPausedOf(msg.sender) validateSenderAccount returns (uint256 newFreezeBalance) { newFreezeBalance = _unfreeze(msg.sender, currentFreezeBalance, amount); emit Unfreeze(msg.sender, currentFreezeBalance, amount); return newFreezeBalance; } /** * @dev See {IFreezable-freezeFrom}. */ function freezeFrom( address account, uint256 currentFreezeBalance, uint256 amount ) external override whenNotPaused whenNotPausedOf(account) validateSenderRoles(CONSENSUS_ROLE, ADMIN_ROLE) validateAddress(account) returns (uint256 newFreezeBalance) { newFreezeBalance = _freeze(account, currentFreezeBalance, amount); emit FreezeFrom(msg.sender, account, currentFreezeBalance, amount); return newFreezeBalance; } /** * @dev See {IFreezable-unfreezeFrom}. */ function unfreezeFrom( address account, uint256 currentFreezeBalance, uint256 amount ) external override whenNotPaused whenNotPausedOf(account) validateSenderRoles(CONSENSUS_ROLE, ADMIN_ROLE) validateAddress(account) returns (uint256 newFreezeBalance) { newFreezeBalance = _unfreeze(account, currentFreezeBalance, amount); emit UnfreezeFrom(msg.sender, account, currentFreezeBalance, amount); return newFreezeBalance; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override whenNotPaused whenNotAccountsPausedOf(msg.sender, recipient) validateSenderAccount validateAddress(recipient) returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view 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 override whenNotPaused whenNotPausedOf(msg.sender) validateSenderAccount validateAddress(spender) returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. */ function transferFrom( address sender, address recipient, uint256 amount ) external override whenNotPaused whenNotAccountsPausedOf(sender, recipient) validateSenderAccount validateAddresses(sender, recipient) returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][msg.sender]; if (currentAllowance < amount) revert IllegalAllowanceError(); unchecked { _approve(sender, msg.sender, currentAllowance - amount); } return true; } /** * @dev See {IERC20Sec-transferFromSec}. */ function transferFromSec( address sender, address recipient, uint256 currentBalance, uint256 amount ) external override whenNotPaused whenNotAccountsPausedOf(sender, recipient) validateSenderAccount validateAddresses(sender, recipient) returns (bool) { uint256 senderBalance = _balances[sender]; if (senderBalance < amount) revert IllegalArgumentError(); if (senderBalance != currentBalance) revert IllegalBalanceError(); uint256 currentAllowance = _allowances[sender][msg.sender]; if (currentAllowance < amount) revert IllegalAllowanceError(); unchecked { _approve(sender, msg.sender, currentAllowance - amount); _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit TransferFromSec(msg.sender, sender, recipient, amount); return true; } /** * @dev See {IERC20Sec-approveSec}. */ function approveSec( address spender, uint256 currentAllowance, uint256 amount ) external override whenNotPaused whenNotPausedOf(msg.sender) validateSenderAccount validateAddress(spender) returns (bool success) { uint256 currentAllowanceAccount = _allowances[msg.sender][spender]; if (currentAllowanceAccount != currentAllowance) revert IllegalAllowanceError(); _allowances[msg.sender][spender] = amount; emit ApprovalSec(msg.sender, spender, currentAllowanceAccount, amount); return true; } /** * @dev See {IERC20Sec-increaseAllowanceSec}. */ function increaseAllowanceSec( address spender, uint256 currentAllowance, uint256 value ) external override whenNotPaused whenNotPausedOf(msg.sender) validateSenderAccount validateAddress(spender) returns (bool) { uint256 currentAllowanceAccount = _allowances[msg.sender][spender]; if (currentAllowanceAccount != currentAllowance) revert IllegalAllowanceError(); _allowances[msg.sender][spender] = currentAllowanceAccount + value; emit ApprovalIncSec( msg.sender, spender, currentAllowanceAccount, value ); return true; } /** * @dev See {IERC20Sec-decreaseAllowanceSec}. */ function decreaseAllowanceSec( address spender, uint256 currentAllowance, uint256 value ) external override whenNotPaused whenNotPausedOf(msg.sender) validateSenderAccount validateAddress(spender) returns (bool) { uint256 currentAllowanceAccount = _allowances[msg.sender][spender]; if (currentAllowanceAccount < value) revert IllegalArgumentError(); if (currentAllowanceAccount != currentAllowance) revert IllegalAllowanceError(); unchecked { _allowances[msg.sender][spender] = currentAllowanceAccount - value; } emit ApprovalDecSec( msg.sender, spender, currentAllowanceAccount, value ); return true; } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint( address account, uint256 currentAccountBalance, uint256 currentTotalSupply, uint256 amount ) external override whenPaused validateSenderRole(CONSENSUS_ROLE) validateAddress(account) { if (_balances[account] != currentAccountBalance) revert IllegalBalanceError(); if (_totalSupply != currentTotalSupply) revert IllegalTotalSupplyError(); _totalSupply += amount; _balances[account] += amount; emit Mint( msg.sender, account, currentAccountBalance, currentTotalSupply, amount ); } /** * @dev See {IBurnable-burn}. */ function burn( address account, uint256 currentBalance, uint256 currentTotalSupply, uint256 amount ) external override whenPaused validateSenderRoles(CONSENSUS_ROLE, BURNABLE_ROLE) validateAddress(account) returns (uint256 newBalance, uint256) { if (_totalSupply != currentTotalSupply) revert IllegalTotalSupplyError(); uint256 currentAccountBalance = _balances[account]; if (currentAccountBalance != currentBalance) revert IllegalBalanceError(); if (currentAccountBalance < amount) revert IllegalArgumentError(); unchecked { newBalance = currentAccountBalance - amount; } _balances[account] = newBalance; _totalSupply -= amount; emit Burn( msg.sender, account, currentBalance, currentTotalSupply, amount ); return (newBalance, _totalSupply); } /** * @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 { uint256 senderBalance = _balances[sender]; if (senderBalance < amount) revert IllegalArgumentError(); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, 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 { _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets `amount` as the freeze(stake) of `account`. */ function _freeze( address account, uint256 currentFreezeBalance, uint256 amount ) internal returns (uint256 newFreezeBalance) { uint256 currentBalance = _balances[account]; if (currentBalance < amount) revert IllegalArgumentError(); uint256 currentFreeze = _freezes[account]; if (currentFreezeBalance != currentFreeze) revert IllegalBalanceError(); newFreezeBalance = currentFreeze + amount; _freezes[account] = newFreezeBalance; unchecked { _balances[account] = currentBalance - amount; } return newFreezeBalance; } /** * @dev Unfreeze `amount` of `account`. */ function _unfreeze( address account, uint256 currentFreezeBalance, uint256 amount ) internal returns (uint256 newFreezeBalance) { uint256 currentFreeze = _freezes[account]; if (currentFreeze < amount) revert IllegalArgumentError(); if (currentFreezeBalance != currentFreeze) revert IllegalBalanceError(); _balances[account] += amount; unchecked { newFreezeBalance = currentFreeze - amount; } _freezes[account] = newFreezeBalance; return newFreezeBalance; } /** * @dev See withdrawal balance of contract by CONSENSUS_ROLE */ // solhint-disable-next-line function withdrawalBalance(address recepient) external validateSenderRole(CONSENSUS_ROLE) { payable(recepient).transfer(address(this).balance); } // solhint-disable-next-line receive() external payable {} // solhint-disable-next-line fallback() external payable {} }
See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`./
function transfer(address recipient, uint256 amount) public override whenNotPaused whenNotAccountsPausedOf(msg.sender, recipient) validateSenderAccount validateAddress(recipient) returns (bool) { _transfer(msg.sender, recipient, amount); return true; }
6,363,247
./full_match/1/0xBCF9F4c6FC589c89d4aAdE063010D0f5B3733680/sources/contracts/staking/Staking.sol
Slash the indexer stake. Delegated tokens are not subject to slashing. Can only be called by the slasher role. _indexer Address of indexer to slash _tokens Amount of tokens to slash from the indexer stake _reward Amount of reward tokens to send to a beneficiary _beneficiary Address of a beneficiary to receive a reward for the slashing/ Only able to slash a non-zero number of tokens Rewards comes from tokens slashed balance Cannot slash stake of an indexer without any or enough stake Validate beneficiary of slashed tokens Slashing more tokens than freely available (over allocation condition) Unlock locked tokens to avoid the indexer to withdraw them Give the beneficiary a reward for slashing
function slash( address _indexer, uint256 _tokens, uint256 _reward, address _beneficiary ) external override onlySlasher notPartialPaused { Stakes.Indexer storage indexerStake = stakes[_indexer]; require(_tokens > 0, "!tokens"); require(_tokens >= _reward, "rewards>slash"); require(indexerStake.hasTokens(), "!stake"); require(_tokens <= indexerStake.tokensStaked, "slash>stake"); require(_beneficiary != address(0), "!beneficiary"); if (_tokens > indexerStake.tokensAvailable() && indexerStake.tokensLocked > 0) { uint256 tokensOverAllocated = _tokens.sub(indexerStake.tokensAvailable()); uint256 tokensToUnlock = (tokensOverAllocated > indexerStake.tokensLocked) ? indexerStake.tokensLocked : tokensOverAllocated; indexerStake.unlockTokens(tokensToUnlock); } IGraphToken graphToken = graphToken(); if (_reward > 0) { require(graphToken.transfer(_beneficiary, _reward), "!transfer"); } emit StakeSlashed(_indexer, _tokens, _reward, _beneficiary); }
4,905,278
./full_match/1313161554/0x56dD69B679611FCC5dE0FEbd8e65e10A0046d537/sources/contracts/interfaces/IDiamondLoupe.sol
A loupe is a small magnifying glass used to look at diamonds. These functions look at diamonds
interface IDiamondLoupe { pragma solidity 0.8.16; struct Facet { address facetAddress; bytes4[] functionSelectors; } }
13,233,522
/* || THE LEXDAO REGISTRY (TLDR) || version 0.2 DEAR MSG.SENDER(S): / TLDR is a project in beta. // Please audit and use at your own risk. /// Entry into TLDR shall not create an attorney/client relationship. //// Likewise, TLDR should not be construed as legal advice or replacement for professional counsel. ///// STEAL THIS C0D3SL4W || lexDAO || ~presented by Open, ESQ LLC_DAO~ < https://mainnet.aragon.org/#/openesquire/ > */ pragma solidity 0.5.9; /*************** OPENZEPPELIN REFERENCE CONTRACTS - SafeMath, ScribeRole, ERC-20 transactional scripts ***************/ /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract ScribeRole is Context { using Roles for Roles.Role; event ScribeAdded(address indexed account); event ScribeRemoved(address indexed account); Roles.Role private _Scribes; constructor () internal { _addScribe(_msgSender()); } modifier onlyScribe() { require(isScribe(_msgSender()), "ScribeRole: caller does not have the Scribe role"); _; } function isScribe(address account) public view returns (bool) { return _Scribes.has(account); } function renounceScribe() public { _removeScribe(_msgSender()); } function _addScribe(address account) internal { _Scribes.add(account); emit ScribeAdded(account); } function _removeScribe(address account) internal { _Scribes.remove(account); emit ScribeRemoved(account); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @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")); } } /*************** TLDR CONTRACT ***************/ contract TLDR is ScribeRole, ERC20 { // TLDR: internet-native market to wrap & enforce common deal patterns with legal & ethereal security using SafeMath for uint256; // lexDAO references for lexDAOscribe (lexScribe) reputation governance fees (Ξ) address payable public lexDAO; // TLDR (LEX) ERC-20 token references for public inspection address public tldrAddress = address(this); ERC20 tldrToken = ERC20(tldrAddress); string public name = "TLDR"; string public symbol = "LEX"; uint8 public decimals = 18; // counters for lexScribe lexScriptWrapper and registered DDR (rddr) / DC (rdc) uint256 public LSW = 1; // number of lexScriptWrapper enscribed (starting from constructor tldr template) uint256 public RDC; // number of rdc uint256 public RDDR; // number of rddr // mapping for lexScribe reputation governance program mapping(address => uint256) public reputation; // mapping lexScribe reputation points mapping(address => uint256) public lastActionTimestamp; // mapping Unix timestamp of lexScribe governance actions (cooldown) mapping(address => uint256) public lastSuperActionTimestamp; // mapping Unix timestamp of special lexScribe governance actions that require longer cooldown (icedown) // mapping for stored lexScript wrappers and registered digital dollar retainers (DDR / rddr) mapping (uint256 => lexScriptWrapper) public lexScript; // mapping registered lexScript 'wet code' templates mapping (uint256 => DC) public rdc; // mapping rdc call numbers for inspection and signature revocation mapping (uint256 => DDR) public rddr; // mapping rddr call numbers for inspection and digital dollar payments struct lexScriptWrapper { // LSW: rddr lexScript templates maintained by lexScribes address lexScribe; // lexScribe (0x) address that enscribed lexScript template into TLDR / can make subsequent edits (lexVersion) address lexAddress; // (0x) address to receive lexScript wrapper lexFee / adjustable by associated lexScribe string templateTerms; // lexScript template terms to wrap rddr with legal security uint256 lexID; // number to reference in rddr to import lexScript wrapper terms uint256 lexVersion; // version number to mark lexScribe edits uint256 lexRate; // fixed, divisible rate for lexFee in ddrToken type per rddr payment made thereunder / e.g., 100 = 1% lexFee on rddr payDDR payment transaction } struct DC { // Digital Covenant lexScript templates maintained by lexScribes address signatory; // DC signatory (0x) address string templateTerms; // DC templateTerms imported from referenced lexScriptWrapper string signatureDetails; // DC may include signatory name or other supplementary info uint256 lexID; // lexID number reference to include lexScriptWrapper for legal security uint256 dcNumber; // DC number generated on signed covenant registration / identifies DC for signatory revocation function call uint256 timeStamp; // block.timestamp ("now") of DC registration bool revoked; // tracks signatory revocation status on DC } struct DDR { // Digital Dollar Retainer created on lexScript terms maintained by lexScribes / data for registration address client; // rddr client (0x) address address provider; // provider (0x) address that receives ERC-20 payments in exchange for goods or services ERC20 ddrToken; // ERC-20 digital token (0x) address used to transfer digital value on ethereum under rddr / e.g., DAI 'digital dollar' - 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359 string deliverable; // goods or services (deliverable) retained for benefit of ethereum payments uint256 lexID; // lexID number reference to include lexScriptWrapper for legal security / default '1' for generalized rddr lexScript template uint256 ddrNumber; // rddr number generated on DDR registration / identifies rddr for payDDR function calls uint256 timeStamp; // block.timestamp ("now") of registration used to calculate retainerTermination UnixTime uint256 retainerTermination; // termination date of rddr in UnixTime / locks payments to provider / after termination, allows withdrawal of remaining escrow digital value by client on payDDR function uint256 deliverableRate; // rate for rddr deliverables in digital dollar wei amount / 1 = 1000000000000000000 uint256 paid; // tracking amount of designated ERC-20 digital value paid under rddr in wei amount for payCap logic uint256 payCap; // value cap limit on rddr payments in wei amount bool confirmed; // tracks provider countersignature status bool disputed; // tracks digital dispute status from client or provider / if called, locks remainder of escrow rddr payments for reputable lexScribe resolution } constructor(string memory tldrTerms, uint256 tldrLexRate, address tldrLexAddress, address payable tldrLexDAO) public { // deploys TLDR contract with designated lexRate / lexAddress (0x) & stores base lexScript template "1" (lexID) address lexScribe = msg.sender; // TLDR summoner is lexScribe reputation[msg.sender] = 3; // sets TLDR summoner lexScribe reputation to '3' max value lexDAO = tldrLexDAO; // sets initial lexDAO (0x) address uint256 lexID = 1; // default lexID for constructor / general rddr reference, 'tldrTerms' uint256 lexVersion = 0; // initialized version of tldrTerms lexScript[lexID] = lexScriptWrapper( // populates default '1' lexScript data for reference in LSW and rddr lexScribe, tldrLexAddress, tldrTerms, lexID, lexVersion, tldrLexRate); } // TLDR Contract Events event Enscribed(uint256 indexed lexID, uint256 indexed lexVersion, address indexed lexScribe); // triggered on successful LSW creation / edits to LSW event Signed(uint256 indexed lexID, uint256 indexed dcNumber, address indexed signatory); // triggered on successful DC creation / edits to DC event Registered(uint256 indexed ddrNumber, uint256 indexed lexID, address indexed client); // triggered on successful rddr event Confirmed(uint256 indexed ddrNumber, uint256 indexed lexID, address indexed provider); // triggered on succesfful rddr confirmation event Paid(uint256 indexed ddrNumber, uint256 indexed lexID); // triggered on successful rddr payments event Disputed(uint256 indexed ddrNumber); // triggered on rddr dispute event Resolved(uint256 indexed ddrNumber); // triggered on successful rddr dispute resolution /*************** TLDR GOVERNANCE FUNCTIONS ***************/ // restricts lexScribe TLDR reputation governance function calls to once per day (cooldown) modifier cooldown() { require(now.sub(lastActionTimestamp[msg.sender]) > 1 days); // enforces cooldown period _; lastActionTimestamp[msg.sender] = now; // block.timestamp, "now" } // restricts important lexScribe TLDR reputation staking and lexDAO governance function calls to once per 90 days (icedown) modifier icedown() { require(now.sub(lastSuperActionTimestamp[msg.sender]) > 90 days); // enforces icedown period _; lastSuperActionTimestamp[msg.sender] = now; // block.timestamp, "now" } // lexDAO can add new lexScribe to maintain TLDR function addScribe(address account) public { require(msg.sender == lexDAO); _addScribe(account); reputation[account] = 1; } // lexDAO can remove lexScribe from TLDR / slash reputation function removeScribe(address account) public { require(msg.sender == lexDAO); _removeScribe(account); reputation[account] = 0; } // lexDAO can update (0x) address receiving reputation governance stakes (Ξ) / maintaining lexScribe registry function updateLexDAO(address payable newLexDAO) public { require(msg.sender == lexDAO); require(newLexDAO != address(0)); // program safety check / newLexDAO cannot be "0" burn address lexDAO = newLexDAO; // updates lexDAO (0x) address } // lexScribes can stake ether (Ξ) value for TLDR reputation and special TLDR function access (TLDR write privileges, rddr dispute resolution role) function stakeETHreputation() payable public onlyScribe icedown { require(msg.value == 0.1 ether); // tenth of ether (Ξ) fee for staking reputation to lexDAO reputation[msg.sender] = 3; // sets / refreshes lexScribe reputation to '3' max value, 'three strikes, you're out' buffer address(lexDAO).transfer(msg.value); // forwards staked value (Ξ) to designated lexDAO (0x) address } // lexScribes can burn minted LEX value for TLDR reputation function stakeLEXreputation() public onlyScribe icedown { _burn(_msgSender(), 10000000000000000000); // 10 LEX burned reputation[msg.sender] = 3; // sets / refreshes lexScribe reputation to '3' max value, 'three strikes, you're out' buffer } // public check on lexScribe reputation status function isReputable(address x) public view returns (bool) { // returns true if lexScribe is reputable return reputation[x] > 0; } // reputable lexScribes can reduce each other's reputation within cooldown period function reduceScribeRep(address reducedLexScribe) cooldown public { require(isReputable(msg.sender)); // program governance check / lexScribe must be reputable require(msg.sender != reducedLexScribe); // program governance check / cannot reduce own reputation reputation[reducedLexScribe] = reputation[reducedLexScribe].sub(1); // reduces referenced lexScribe reputation by "1" } // reputable lexScribes can repair each other's reputation within cooldown period function repairScribeRep(address repairedLexScribe) cooldown public { require(isReputable(msg.sender)); // program governance check / lexScribe must be reputable require(msg.sender != repairedLexScribe); // program governance check / cannot repair own reputation require(reputation[repairedLexScribe] < 3); // program governance check / cannot repair fully reputable lexScribe require(reputation[repairedLexScribe] > 0); // program governance check / cannot repair disreputable lexScribe / induct non-staked lexScribe reputation[repairedLexScribe] = reputation[repairedLexScribe].add(1); // repairs reputation by "1" } /*************** TLDR LEXSCRIBE FUNCTIONS ***************/ // reputable lexScribes can register lexScript legal wrappers on TLDR and program ERC-20 lexFees associated with lexID / receive LEX mint, "1" function writeLexScript(string memory templateTerms, uint256 lexRate, address lexAddress) public { require(isReputable(msg.sender)); // program governance check / lexScribe must be reputable uint256 lexID = LSW.add(1); // reflects new lexScript value for tracking lexScript wrappers uint256 lexVersion = 0; // initalized lexVersion, "0" LSW = LSW.add(1); // counts new entry to LSW lexScript[lexID] = lexScriptWrapper( // populate lexScript data for rddr / rdc usage msg.sender, lexAddress, templateTerms, lexID, lexVersion, lexRate); _mint(msg.sender, 1000000000000000000); // mints lexScribe "1" LEX for contribution to TLDR emit Enscribed(lexID, lexVersion, msg.sender); } // lexScribes can update TLDR lexScript wrappers with new templateTerms and (0x) newLexAddress / versions up LSW function editLexScript(uint256 lexID, string memory templateTerms, address lexAddress) public { lexScriptWrapper storage lS = lexScript[lexID]; // retrieve LSW data require(msg.sender == lS.lexScribe); // program safety check / authorization uint256 lexVersion = lS.lexVersion.add(1); // updates lexVersion lexScript[lexID] = lexScriptWrapper( // populates updated lexScript data for rddr / rdc usage msg.sender, lexAddress, templateTerms, lexID, lexVersion, lS.lexRate); emit Enscribed(lexID, lexVersion, msg.sender); } /*************** TLDR MARKET FUNCTIONS ***************/ // public can sign and associate (0x) ethereum identity with lexScript digital covenant wrapper function signDC(uint256 lexID, string memory signatureDetails) public { // sign Digital Covenant with (0x) address require(lexID > (0)); // program safety check require(lexID <= LSW); // program safety check lexScriptWrapper storage lS = lexScript[lexID]; // retrieve LSW data uint256 dcNumber = RDC.add(1); // reflects new rdc value for public inspection and signature revocation RDC = RDC.add(1); // counts new entry to RDC rdc[dcNumber] = DC( // populates rdc data msg.sender, lS.templateTerms, signatureDetails, lexID, dcNumber, now, false); emit Signed(lexID, dcNumber, msg.sender); } // registered DC signatories can revoke (0x) signature function revokeDC(uint256 dcNumber) public { // revoke Digital Covenant signature with (0x) address DC storage dc = rdc[dcNumber]; // retrieve rdc data require(msg.sender == dc.signatory); // program safety check / authorization rdc[dcNumber] = DC(// updates rdc data msg.sender, "Signature Revoked", // replaces Digital Covenant terms with revocation message dc.signatureDetails, dc.lexID, dc.dcNumber, now, // updates to revocation timestamp true); emit Signed(dc.lexID, dcNumber, msg.sender); } // rddr client can register DDR with TLDR lexScripts (lexID) function registerDDR( // rddr address client, address provider, ERC20 ddrToken, string memory deliverable, uint256 retainerDuration, uint256 deliverableRate, uint256 payCap, uint256 lexID) public { require(lexID > (0)); // program safety check require(lexID <= LSW); // program safety check require(deliverableRate <= payCap); // program safety check / economics require(msg.sender == client); // program safety check / authorization / client signs TLDR transaction registering ddr offer / designates provider for confirmation uint256 ddrNumber = RDDR.add(1); // reflects new rddr value for inspection and escrow management uint256 retainerTermination = now.add(retainerDuration); // rddr termination date in UnixTime, "now" block.timestamp + retainerDuration RDDR = RDDR.add(1); // counts new entry to RDDR rddr[ddrNumber] = DDR( // populate rddr data client, provider, ddrToken, deliverable, lexID, ddrNumber, now, // block.timestamp, "now" retainerTermination, deliverableRate, 0, payCap, false, false); emit Registered(ddrNumber, lexID, msg.sender); } // rddr provider can confirm rddr offer and countersign ddrNumber / trigger escrow deposit from rddr client in approved payCap amount function confirmDDR(uint256 ddrNumber) public { DDR storage ddr = rddr[ddrNumber]; // retrieve rddr data require(ddr.confirmed == false); // program safety check / status require(now <= ddr.retainerTermination); // program safety check / time require(msg.sender == ddr.provider); // program safety check / authorization ddr.confirmed = true; // reflect rddr provider countersignature ddr.ddrToken.transferFrom(ddr.client, address(this), ddr.payCap); // escrows payCap amount in approved ddrToken into TLDR for rddr payments and/or lexScribe resolution emit Confirmed(ddrNumber, ddr.lexID, msg.sender); } // rddr client can call to delegate role function delegateDDRclient(uint256 ddrNumber, address clientDelegate) public { DDR storage ddr = rddr[ddrNumber]; // retrieve rddr data require(ddr.disputed == false); // program safety check / status require(now <= ddr.retainerTermination); // program safety check / time require(msg.sender == ddr.client); // program safety check / authorization require(ddr.paid < ddr.payCap); // program safety check / economics ddr.client = clientDelegate; // updates rddr client address to delegate } // rddr parties can initiate dispute and lock escrowed remainder of rddr payCap in TLDR until resolution by reputable lexScribe function disputeDDR(uint256 ddrNumber) public { DDR storage ddr = rddr[ddrNumber]; // retrieve rddr data require(ddr.confirmed == true); // program safety check / status require(ddr.disputed == false); // program safety check / status require(now <= ddr.retainerTermination); // program safety check / time require(msg.sender == ddr.client || msg.sender == ddr.provider); // program safety check / authorization require(ddr.paid < ddr.payCap); // program safety check / economics ddr.disputed = true; // updates rddr value to reflect dispute status, "true" emit Disputed(ddrNumber); } // reputable lexScribe can resolve rddr dispute with division of remaining payCap amount in wei accounting for 5% fee / receive fee + LEX mint, "1" function resolveDDR(uint256 ddrNumber, uint256 clientAward, uint256 providerAward) public { DDR storage ddr = rddr[ddrNumber]; // retrieve rddr data uint256 ddRemainder = ddr.payCap.sub(ddr.paid); // alias remainder rddr wei amount for rddr resolution reference uint256 resolutionFee = ddRemainder.div(20); // calculates 5% lexScribe dispute resolution fee require(ddr.disputed == true); // program safety check / status require(clientAward.add(providerAward) == ddRemainder.sub(resolutionFee)); // program safety check / economics require(msg.sender != ddr.client); // program safety check / authorization / client cannot resolve own dispute as lexScribe require(msg.sender != ddr.provider); // program safety check / authorization / provider cannot resolve own dispute as lexScribe require(isReputable(msg.sender)); // program governance check / resolving lexScribe must be reputable require(balanceOf(msg.sender) >= 5000000000000000000); // program governance check / resolving lexScribe must have at least "5" LEX balance ddr.ddrToken.transfer(ddr.client, clientAward); // executes ERC-20 award transfer to rddr client ddr.ddrToken.transfer(ddr.provider, providerAward); // executes ERC-20 award transfer to rddr provider ddr.ddrToken.transfer(msg.sender, resolutionFee); // executes ERC-20 fee transfer to resolving lexScribe _mint(msg.sender, 1000000000000000000); // mints resolving lexScribe "1" LEX for contribution to TLDR ddr.paid = ddr.paid.add(ddRemainder); // tallies remainder to paid wei amount to reflect rddr closure emit Resolved(ddrNumber); } // client can call to pay rddr on TLDR function payDDR(uint256 ddrNumber) public { // releases escrowed ddrToken deliverableRate amount to provider (0x) address / lexFee for attached lexID lexAddress DDR storage ddr = rddr[ddrNumber]; // retrieve rddr data lexScriptWrapper storage lS = lexScript[ddr.lexID]; // retrieve LSW data require(ddr.confirmed == true); // program safety check / status require(ddr.disputed == false); // program safety check / status require(now <= ddr.retainerTermination); // program safety check / time require(msg.sender == ddr.client); // program safety check / authorization require(ddr.paid.add(ddr.deliverableRate) <= ddr.payCap); // program safety check / economics uint256 lexFee = ddr.deliverableRate.div(lS.lexRate); // derives lexFee from rddr deliverableRate ddr.ddrToken.transfer(ddr.provider, ddr.deliverableRate.sub(lexFee)); // executes ERC-20 transfer to rddr provider in deliverableRate amount ddr.ddrToken.transfer(lS.lexAddress, lexFee); // executes ERC-20 transfer of lexFee to (0x) lexAddress identified in lexID ddr.paid = ddr.paid.add(ddr.deliverableRate); // tracks total ERC-20 wei amount paid under rddr / used to calculate rddr remainder emit Paid(ddr.ddrNumber, ddr.lexID); } // client can call to withdraw rddr remainder on TLDR after termination function withdrawRemainder(uint256 ddrNumber) public { // releases escrowed ddrToken deliverableRate amount to provider (0x) address DDR storage ddr = rddr[ddrNumber]; // retrieve rddr data require(ddr.confirmed == true); // program safety check / status require(ddr.disputed == false); // program safety check / status require(now >= ddr.retainerTermination); // program safety check / time require(msg.sender == ddr.client); // program safety check / authorization uint256 remainder = ddr.payCap.sub(ddr.paid); // derive rddr remainder require(remainder > 0); // program safety check / economics ddr.ddrToken.transfer(ddr.client, remainder); // executes ERC-20 transfer to rddr provider in escrow remainder amount ddr.paid = ddr.paid.add(remainder); // tallies remainder to paid wei amount to reflect rddr closure } }
reputable lexScribe can resolve rddr dispute with division of remaining payCap amount in wei accounting for 5% fee / receive fee + LEX mint, "1"
function resolveDDR(uint256 ddrNumber, uint256 clientAward, uint256 providerAward) public { emit Resolved(ddrNumber); }
2,555,234
// SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.sol'; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @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 Context, IAccessControlUpgradeable, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _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]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( 'AccessControl: account ', Strings.toHexString(uint160(account), 20), ' is missing role ', Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), 'AccessControl: can only renounce roles for self'); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = '0123456789abcdef'; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return '0'; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, 'Strings: hex length insufficient'); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './IERC165.sol'; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @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: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; /** * @title SP1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contracts with storage. */ abstract contract SP1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Modifiers ============ /** * @dev Modifier to ensure the STARK key is allowed. */ modifier onlyAllowedKey( uint256 starkKey ) { require(_ALLOWED_STARK_KEYS_[starkKey], 'SP1Storage: STARK key is not on the allowlist'); _; } /** * @dev Modifier to ensure the recipient is allowed. */ modifier onlyAllowedRecipient( address recipient ) { require(_ALLOWED_RECIPIENTS_[recipient], 'SP1Storage: Recipient is not on the allowlist'); _; } // ============ Storage ============ mapping(uint256 => bool) internal _ALLOWED_STARK_KEYS_; mapping(address => bool) internal _ALLOWED_RECIPIENTS_; /// @dev Note that withdrawals are always permitted if the amount is in excess of the borrowed /// amount. Also, this approval only applies to the primary ERC20 token, `TOKEN`. uint256 internal _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_; /// @dev Note that this is different from _IS_BORROWING_RESTRICTED_ in LiquidityStakingV1. bool internal _IS_BORROWING_RESTRICTED_; /// @dev Mapping from args hash to timestamp. mapping(bytes32 => uint256) internal _QUEUED_FORCED_TRADE_TIMESTAMPS_; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @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. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { Math } from '../../../utils/Math.sol'; import { SP1Storage } from './SP1Storage.sol'; /** * @title SP1Getters * @author dYdX * * @dev Simple external getter functions. */ abstract contract SP1Getters is SP1Storage { using SafeMath for uint256; // ============ External Functions ============ /** * @notice Check whether a STARK key is on the allowlist for exchange operations. * * @param starkKey The STARK key to check. * * @return Boolean `true` if the STARK key is allowed, otherwise `false`. */ function isStarkKeyAllowed( uint256 starkKey ) external view returns (bool) { return _ALLOWED_STARK_KEYS_[starkKey]; } /** * @notice Check whether a recipient is on the allowlist to receive withdrawals. * * @param recipient The recipient to check. * * @return Boolean `true` if the recipient is allowed, otherwise `false`. */ function isRecipientAllowed( address recipient ) external view returns (bool) { return _ALLOWED_RECIPIENTS_[recipient]; } /** * @notice Get the amount approved by the guardian for external withdrawals. * Note that withdrawals are always permitted if the amount is in excess of the borrowed amount. * * @return The amount approved for external withdrawals. */ function getApprovedAmountForExternalWithdrawal() external view returns (uint256) { return _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_; } /** * @notice Check whether this borrower contract is restricted from new borrowing, as well as * restricted from depositing borrowed funds to the exchange. * * @return Boolean `true` if the borrower is restricted, otherwise `false`. */ function isBorrowingRestricted() external view returns (bool) { return _IS_BORROWING_RESTRICTED_; } /** * @notice Get the timestamp at which a forced trade request was queued. * * @param argsHash The hash of the forced trade request args. * * @return Timestamp at which the forced trade was queued, or zero, if it was not queued or was * vetoed by the VETO_GUARDIAN_ROLE. */ function getQueuedForcedTradeTimestamp( bytes32 argsHash ) external view returns (uint256) { return _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash]; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol'; /** * @title Math * @author dYdX * * @dev Library for non-standard Math functions. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /** * @dev Return `ceil(numerator / denominator)`. */ function divRoundUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return numerator.sub(1).div(denominator).add(1); } /** * @dev Returns the minimum between a and b. */ function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the maximum between a and b. */ function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts // // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { IERC20 } from '../../interfaces/IERC20.sol'; import { ILiquidityStakingV1 } from '../../interfaces/ILiquidityStakingV1.sol'; import { IMerkleDistributorV1 } from '../../interfaces/IMerkleDistributorV1.sol'; import { IStarkPerpetual } from '../../interfaces/IStarkPerpetual.sol'; import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol'; import { SP1Withdrawals } from './impl/SP1Withdrawals.sol'; import { SP1Getters } from './impl/SP1Getters.sol'; import { SP1Guardian } from './impl/SP1Guardian.sol'; import { SP1Owner } from './impl/SP1Owner.sol'; /** * @title StarkProxyV1 * @author dYdX * * @notice Proxy contract allowing a LiquidityStaking borrower to use borrowed funds (as well as * their own funds, if desired) on the dYdX L2 exchange. Restrictions are put in place to * prevent borrowed funds being used outside the exchange. Furthermore, a guardian address is * specified which has the ability to restrict borrows and make repayments. * * Owner actions may be delegated to various roles as defined in SP1Roles. Other actions are * available to guardian roles, to be nominated by dYdX governance. */ contract StarkProxyV1 is SP1Guardian, SP1Owner, SP1Withdrawals, SP1Getters { using SafeERC20 for IERC20; // ============ Constructor ============ constructor( ILiquidityStakingV1 liquidityStaking, IStarkPerpetual starkPerpetual, IERC20 token, IMerkleDistributorV1 merkleDistributor ) SP1Guardian(liquidityStaking, starkPerpetual, token) SP1Withdrawals(merkleDistributor) {} // ============ External Functions ============ function initialize(address guardian) external initializer { __SP1Roles_init(guardian); TOKEN.safeApprove(address(LIQUIDITY_STAKING), uint256(-1)); TOKEN.safeApprove(address(STARK_PERPETUAL), uint256(-1)); } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 1; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @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: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ILiquidityStakingV1 * @author dYdX * * @notice Partial interface for LiquidityStakingV1. */ interface ILiquidityStakingV1 { function getToken() external view virtual returns (address); function getBorrowedBalance(address borrower) external view virtual returns (uint256); function getBorrowerDebtBalance(address borrower) external view virtual returns (uint256); function isBorrowingRestrictedForBorrower(address borrower) external view virtual returns (bool); function getTimeRemainingInEpoch() external view virtual returns (uint256); function inBlackoutWindow() external view virtual returns (bool); // LS1Borrowing function borrow(uint256 amount) external virtual; function repayBorrow(address borrower, uint256 amount) external virtual; function getAllocatedBalanceCurrentEpoch(address borrower) external view virtual returns (uint256); function getAllocatedBalanceNextEpoch(address borrower) external view virtual returns (uint256); function getBorrowableAmount(address borrower) external view virtual returns (uint256); // LS1DebtAccounting function repayDebt(address borrower, uint256 amount) external virtual; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title IMerkleDistributorV1 * @author dYdX * * @notice Partial interface for the MerkleDistributorV1 contract. */ interface IMerkleDistributorV1 { function getIpnsName() external virtual view returns (string memory); function getRewardsParameters() external virtual view returns (uint256, uint256, uint256); function getActiveRoot() external virtual view returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid); function getNextRootEpoch() external virtual view returns (uint256); function claimRewards( uint256 cumulativeAmount, bytes32[] calldata merkleProof ) external returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title IStarkPerpetual * @author dYdX * * @notice Partial interface for the StarkPerpetual contract, for accessing the dYdX L2 exchange. * @dev See https://github.com/starkware-libs/starkex-contracts */ interface IStarkPerpetual { function registerUser( address ethKey, uint256 starkKey, bytes calldata signature ) external; function deposit( uint256 starkKey, uint256 assetType, uint256 vaultId, uint256 quantizedAmount ) external; function withdraw(uint256 starkKey, uint256 assetType) external; function forcedWithdrawalRequest( uint256 starkKey, uint256 vaultId, uint256 quantizedAmount, bool premiumCost ) external; function forcedTradeRequest( uint256 starkKeyA, uint256 starkKeyB, uint256 vaultIdA, uint256 vaultIdB, uint256 collateralAssetId, uint256 syntheticAssetId, uint256 amountCollateral, uint256 amountSynthetic, bool aIsBuyingSynthetic, uint256 submissionExpirationTime, uint256 nonce, bytes calldata signature, bool premiumCost ) external; function mainAcceptGovernance() external; function proxyAcceptGovernance() external; function mainRemoveGovernor(address governorForRemoval) external; function proxyRemoveGovernor(address governorForRemoval) external; function registerAssetConfigurationChange(uint256 assetId, bytes32 configHash) external; function applyAssetConfigurationChange(uint256 assetId, bytes32 configHash) external; function registerGlobalConfigurationChange(bytes32 configHash) external; function applyGlobalConfigurationChange(bytes32 configHash) external; function getEthKey(uint256 starkKey) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } 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.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IMerkleDistributorV1 } from '../../../interfaces/IMerkleDistributorV1.sol'; import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol'; import { SP1Exchange } from './SP1Exchange.sol'; /** * @title SP1Withdrawals * @author dYdX * * @dev Actions which may be called only by WITHDRAWAL_OPERATOR_ROLE. Allows for withdrawing * funds from the contract to external addresses that were approved by OWNER_ROLE. */ abstract contract SP1Withdrawals is SP1Exchange { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ IMerkleDistributorV1 public immutable MERKLE_DISTRIBUTOR; // ============ Events ============ event ExternalWithdrewToken( address recipient, uint256 amount ); event ExternalWithdrewOtherToken( address token, address recipient, uint256 amount ); event ExternalWithdrewEther( address recipient, uint256 amount ); // ============ Constructor ============ constructor( IMerkleDistributorV1 merkleDistributor ) { MERKLE_DISTRIBUTOR = merkleDistributor; } // ============ External Functions ============ /** * @notice Claim rewards from the Merkle distributor. They will be held in this contract until * withdrawn by the WITHDRAWAL_OPERATOR_ROLE. * * @param cumulativeAmount The total all-time rewards this contract has earned. * @param merkleProof The Merkle proof for this contract address and cumulative amount. * * @return The amount of new reward received. */ function claimRewardsFromMerkleDistributor( uint256 cumulativeAmount, bytes32[] calldata merkleProof ) external nonReentrant onlyRole(WITHDRAWAL_OPERATOR_ROLE) returns (uint256) { return MERKLE_DISTRIBUTOR.claimRewards(cumulativeAmount, merkleProof); } /** * @notice Withdraw a token amount in excess of the borrowed balance, or an amount approved by * the GUARDIAN_ROLE. * * The contract may hold an excess balance if, for example, additional funds were added by the * contract owner for use with the same exchange account, or if profits were earned from * activity on the exchange. * * @param recipient The recipient to receive tokens. Must be authorized by OWNER_ROLE. */ function externalWithdrawToken( address recipient, uint256 amount ) external nonReentrant onlyRole(WITHDRAWAL_OPERATOR_ROLE) onlyAllowedRecipient(recipient) { // If we are approved for the full amount, then skip the borrowed balance check. uint256 approvedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_; if (approvedAmount >= amount) { _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = approvedAmount.sub(amount); } else { uint256 owedBalance = getBorrowedAndDebtBalance(); uint256 tokenBalance = getTokenBalance(); require(tokenBalance > owedBalance, 'SP1Withdrawals: No withdrawable balance'); uint256 availableBalance = tokenBalance.sub(owedBalance); require(amount <= availableBalance, 'SP1Withdrawals: Amount exceeds withdrawable balance'); // Always decrease the approval amount. _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = 0; } TOKEN.safeTransfer(recipient, amount); emit ExternalWithdrewToken(recipient, amount); } /** * @notice Withdraw any ERC20 token balance other than the token used for borrowing. * * @param recipient The recipient to receive tokens. Must be authorized by OWNER_ROLE. */ function externalWithdrawOtherToken( address token, address recipient, uint256 amount ) external nonReentrant onlyRole(WITHDRAWAL_OPERATOR_ROLE) onlyAllowedRecipient(recipient) { require( token != address(TOKEN), 'SP1Withdrawals: Cannot use this function to withdraw borrowed token' ); IERC20(token).safeTransfer(recipient, amount); emit ExternalWithdrewOtherToken(token, recipient, amount); } /** * @notice Withdraw any ether. * * Note: The contract is not expected to hold Ether so this is not normally needed. * * @param recipient The recipient to receive Ether. Must be authorized by OWNER_ROLE. */ function externalWithdrawEther( address recipient, uint256 amount ) external nonReentrant onlyRole(WITHDRAWAL_OPERATOR_ROLE) onlyAllowedRecipient(recipient) { payable(recipient).transfer(amount); emit ExternalWithdrewEther(recipient, amount); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol'; import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol'; import { SP1Borrowing } from './SP1Borrowing.sol'; import { SP1Exchange } from './SP1Exchange.sol'; /** * @title SP1Guardian * @author dYdX * * @dev Defines guardian powers, to be owned or delegated by dYdX governance. */ abstract contract SP1Guardian is SP1Borrowing, SP1Exchange { using SafeMath for uint256; // ============ Events ============ event BorrowingRestrictionChanged( bool isBorrowingRestricted ); event GuardianVetoedForcedTradeRequest( bytes32 argsHash ); event GuardianUpdateApprovedAmountForExternalWithdrawal( uint256 amount ); // ============ Constructor ============ constructor( ILiquidityStakingV1 liquidityStaking, IStarkPerpetual starkPerpetual, IERC20 token ) SP1Borrowing(liquidityStaking, token) SP1Exchange(starkPerpetual) {} // ============ External Functions ============ /** * @notice Approve an additional amount for external withdrawal by WITHDRAWAL_OPERATOR_ROLE. * * @param amount The additional amount to approve for external withdrawal. * * @return The new amount approved for external withdrawal. */ function increaseApprovedAmountForExternalWithdrawal( uint256 amount ) external nonReentrant onlyRole(GUARDIAN_ROLE) returns (uint256) { uint256 newApprovedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_.add( amount ); _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = newApprovedAmount; emit GuardianUpdateApprovedAmountForExternalWithdrawal(newApprovedAmount); return newApprovedAmount; } /** * @notice Set the approved amount for external withdrawal to zero. * * @return The amount that was previously approved for external withdrawal. */ function resetApprovedAmountForExternalWithdrawal() external nonReentrant onlyRole(GUARDIAN_ROLE) returns (uint256) { uint256 previousApprovedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_; _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = 0; emit GuardianUpdateApprovedAmountForExternalWithdrawal(0); return previousApprovedAmount; } /** * @notice Guardian method to restrict borrowing or depositing borrowed funds to the exchange. */ function guardianSetBorrowingRestriction( bool isBorrowingRestricted ) external nonReentrant onlyRole(GUARDIAN_ROLE) { _IS_BORROWING_RESTRICTED_ = isBorrowingRestricted; emit BorrowingRestrictionChanged(isBorrowingRestricted); } /** * @notice Guardian method to repay this contract's borrowed balance, using this contract's funds. * * @param amount Amount to repay. */ function guardianRepayBorrow( uint256 amount ) external nonReentrant onlyRole(GUARDIAN_ROLE) { _repayBorrow(amount, true); } /** * @notice Guardian method to repay a debt balance owed by the borrower. * * @param amount Amount to repay. */ function guardianRepayDebt( uint256 amount ) external nonReentrant onlyRole(GUARDIAN_ROLE) { _repayDebt(amount, true); } /** * @notice Guardian method to trigger a withdrawal. This will transfer funds from StarkPerpetual * to this contract. This requires a (slow) withdrawal from L2 to have been previously processed. * * Note: This function is intentionally not protected by the onlyAllowedKey modifier. * * @return The ERC20 token amount received by this contract. */ function guardianWithdrawFromExchange( uint256 starkKey, uint256 assetType ) external nonReentrant onlyRole(GUARDIAN_ROLE) returns (uint256) { return _withdrawFromExchange(starkKey, assetType, true); } /** * @notice Guardian method to trigger a forced withdrawal request. * Reverts if the borrower has no overdue debt. * * Note: This function is intentionally not protected by the onlyAllowedKey modifier. */ function guardianForcedWithdrawalRequest( uint256 starkKey, uint256 vaultId, uint256 quantizedAmount, bool premiumCost ) external nonReentrant onlyRole(GUARDIAN_ROLE) { require( getDebtBalance() > 0, 'SP1Guardian: Cannot call forced action if borrower has no overdue debt' ); _forcedWithdrawalRequest( starkKey, vaultId, quantizedAmount, premiumCost, true // isGuardianAction ); } /** * @notice Guardian method to trigger a forced trade request. * Reverts if the borrower has no overdue debt. * * Note: This function is intentionally not protected by the onlyAllowedKey modifier. */ function guardianForcedTradeRequest( uint256[12] calldata args, bytes calldata signature ) external nonReentrant onlyRole(GUARDIAN_ROLE) { require( getDebtBalance() > 0, 'SP1Guardian: Cannot call forced action if borrower has no overdue debt' ); _forcedTradeRequest(args, signature, true); } /** * @notice Guardian method to prevent queued forced trade requests from being executed. * * May only be called by VETO_GUARDIAN_ROLE. * * @param argsHashes An array of hashes for each forced trade request to veto. */ function guardianVetoForcedTradeRequests( bytes32[] calldata argsHashes ) external nonReentrant onlyRole(VETO_GUARDIAN_ROLE) { for (uint256 i = 0; i < argsHashes.length; i++) { bytes32 argsHash = argsHashes[i]; _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = 0; emit GuardianVetoedForcedTradeRequest(argsHash); } } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol'; import { SP1Borrowing } from './SP1Borrowing.sol'; import { SP1Exchange } from './SP1Exchange.sol'; /** * @title SP1Owner * @author dYdX * * @dev Actions which may be called only by OWNER_ROLE. These include actions with a larger amount * of control over the funds held by the contract. */ abstract contract SP1Owner is SP1Borrowing, SP1Exchange { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice Time that must elapse before a queued forced trade request can be submitted. uint256 public constant FORCED_TRADE_WAITING_PERIOD = 7 days; /// @notice Max time that may elapse after the waiting period before a queued forced trade /// request expires. uint256 public constant FORCED_TRADE_GRACE_PERIOD = 7 days; // ============ Events ============ event UpdatedStarkKey( uint256 starkKey, bool isAllowed ); event UpdatedExternalRecipient( address recipient, bool isAllowed ); event QueuedForcedTradeRequest( uint256[12] args, bytes32 argsHash ); // ============ External Functions ============ /** * @notice Allow exchange functions to be called for a particular STARK key. * * Will revert if the STARK key is not registered to this contract's address on the * StarkPerpetual contract. * * @param starkKey The STARK key to allow. */ function allowStarkKey( uint256 starkKey ) external nonReentrant onlyRole(OWNER_ROLE) { // This will revert with 'USER_UNREGISTERED' if the STARK key was not registered. address ethKey = STARK_PERPETUAL.getEthKey(starkKey); // Require the STARK key to be registered to this contract before we allow it to be used. require(ethKey == address(this), 'SP1Owner: STARK key not registered to this contract'); require(!_ALLOWED_STARK_KEYS_[starkKey], 'SP1Owner: STARK key already allowed'); _ALLOWED_STARK_KEYS_[starkKey] = true; emit UpdatedStarkKey(starkKey, true); } /** * @notice Remove a STARK key from the allowed list. * * @param starkKey The STARK key to disallow. */ function disallowStarkKey( uint256 starkKey ) external nonReentrant onlyRole(OWNER_ROLE) { require(_ALLOWED_STARK_KEYS_[starkKey], 'SP1Owner: STARK key already disallowed'); _ALLOWED_STARK_KEYS_[starkKey] = false; emit UpdatedStarkKey(starkKey, false); } /** * @notice Allow withdrawals of excess funds to be made to a particular recipient. * * @param recipient The recipient to allow. */ function allowExternalRecipient( address recipient ) external nonReentrant onlyRole(OWNER_ROLE) { require(!_ALLOWED_RECIPIENTS_[recipient], 'SP1Owner: Recipient already allowed'); _ALLOWED_RECIPIENTS_[recipient] = true; emit UpdatedExternalRecipient(recipient, true); } /** * @notice Remove a recipient from the allowed list. * * @param recipient The recipient to disallow. */ function disallowExternalRecipient( address recipient ) external nonReentrant onlyRole(OWNER_ROLE) { require(_ALLOWED_RECIPIENTS_[recipient], 'SP1Owner: Recipient already disallowed'); _ALLOWED_RECIPIENTS_[recipient] = false; emit UpdatedExternalRecipient(recipient, false); } /** * @notice Set ERC20 token allowance for the exchange contract. * * @param token The ERC20 token to set the allowance for. * @param amount The new allowance amount. */ function setExchangeContractAllowance( address token, uint256 amount ) external nonReentrant onlyRole(OWNER_ROLE) { // SafeERC20 safeApprove requires setting to zero first. IERC20(token).safeApprove(address(STARK_PERPETUAL), 0); IERC20(token).safeApprove(address(STARK_PERPETUAL), amount); } /** * @notice Set ERC20 token allowance for the staking contract. * * @param token The ERC20 token to set the allowance for. * @param amount The new allowance amount. */ function setStakingContractAllowance( address token, uint256 amount ) external nonReentrant onlyRole(OWNER_ROLE) { // SafeERC20 safeApprove requires setting to zero first. IERC20(token).safeApprove(address(LIQUIDITY_STAKING), 0); IERC20(token).safeApprove(address(LIQUIDITY_STAKING), amount); } /** * @notice Request a forced withdrawal from the exchange. * * @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE. * @param vaultId The exchange position ID for the account to deposit to. * @param quantizedAmount The withdrawal amount denominated in the exchange base units. * @param premiumCost Whether to pay a higher fee for faster inclusion in certain scenarios. */ function forcedWithdrawalRequest( uint256 starkKey, uint256 vaultId, uint256 quantizedAmount, bool premiumCost ) external nonReentrant onlyRole(OWNER_ROLE) onlyAllowedKey(starkKey) { _forcedWithdrawalRequest(starkKey, vaultId, quantizedAmount, premiumCost, false); } /** * @notice Queue a forced trade request to be submitted after the waiting period. * * @param args Arguments for the forced trade request. */ function queueForcedTradeRequest( uint256[12] calldata args ) external nonReentrant onlyRole(OWNER_ROLE) { bytes32 argsHash = keccak256(abi.encodePacked(args)); _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = block.timestamp; emit QueuedForcedTradeRequest(args, argsHash); } /** * @notice Submit a forced trade request that was previously queued. * * @param args Arguments for the forced trade request. * @param signature The signature of the counterparty to the trade. */ function forcedTradeRequest( uint256[12] calldata args, bytes calldata signature ) external nonReentrant onlyRole(OWNER_ROLE) onlyAllowedKey(args[0]) // starkKeyA { bytes32 argsHash = keccak256(abi.encodePacked(args)); uint256 timestamp = _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash]; require( timestamp != 0, 'SP1Owner: Forced trade not queued or was vetoed' ); uint256 elapsed = block.timestamp.sub(timestamp); require( elapsed >= FORCED_TRADE_WAITING_PERIOD, 'SP1Owner: Waiting period has not elapsed for forced trade' ); require( elapsed <= FORCED_TRADE_WAITING_PERIOD.add(FORCED_TRADE_GRACE_PERIOD), 'SP1Owner: Grace period has elapsed for forced trade' ); _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = 0; _forcedTradeRequest(args, signature, false); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev 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'); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol'; import { SP1Balances } from './SP1Balances.sol'; /** * @title SP1Exchange * @author dYdX * * @dev Handles calls to the StarkPerpetual contract, for interacting with the dYdX L2 exchange. * * Standard exchange operation is handled by EXCHANGE_OPERATOR_ROLE. The “forced” actions can only * be called by the OWNER_ROLE or GUARDIAN_ROLE. Some other functions are also callable by * the GUARDIAN_ROLE. * * See SP1Roles, SP1Guardian, SP1Owner, and SP1Withdrawals. */ abstract contract SP1Exchange is SP1Balances { using SafeMath for uint256; // ============ Constants ============ IStarkPerpetual public immutable STARK_PERPETUAL; // ============ Events ============ event DepositedToExchange( uint256 starkKey, uint256 starkAssetType, uint256 starkVaultId, uint256 tokenAmount ); event WithdrewFromExchange( uint256 starkKey, uint256 starkAssetType, uint256 tokenAmount, bool isGuardianAction ); /// @dev Limited fields included. Details can be retrieved from Starkware logs if needed. event RequestedForcedWithdrawal( uint256 starkKey, uint256 vaultId, bool isGuardianAction ); /// @dev Limited fields included. Details can be retrieved from Starkware logs if needed. event RequestedForcedTrade( uint256 starkKey, uint256 vaultId, bool isGuardianAction ); // ============ Constructor ============ constructor( IStarkPerpetual starkPerpetual ) { STARK_PERPETUAL = starkPerpetual; } // ============ External Functions ============ /** * @notice Deposit funds to the exchange. * * IMPORTANT: The caller is responsible for providing `quantizedAmount` in the right units. * Currently, the exchange collateral is USDC, denominated in ERC20 token units, but * this could change. * * @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE. * @param assetType The exchange asset ID for the asset to deposit. * @param vaultId The exchange position ID for the account to deposit to. * @param quantizedAmount The deposit amount denominated in the exchange base units. * * @return The ERC20 token amount spent. */ function depositToExchange( uint256 starkKey, uint256 assetType, uint256 vaultId, uint256 quantizedAmount ) external nonReentrant onlyRole(EXCHANGE_OPERATOR_ROLE) onlyAllowedKey(starkKey) returns (uint256) { // Deposit and get the deposited token amount. uint256 startingBalance = getTokenBalance(); STARK_PERPETUAL.deposit(starkKey, assetType, vaultId, quantizedAmount); uint256 endingBalance = getTokenBalance(); uint256 tokenAmount = startingBalance.sub(endingBalance); // Disallow depositing borrowed funds to the exchange if the guardian has restricted borrowing. if (_IS_BORROWING_RESTRICTED_) { require( endingBalance >= getBorrowedAndDebtBalance(), 'SP1Borrowing: Cannot deposit borrowed funds to the exchange while Restricted' ); } emit DepositedToExchange(starkKey, assetType, vaultId, tokenAmount); return tokenAmount; } /** * @notice Trigger a withdrawal of account funds held in the exchange contract. This can be * called after a (slow) withdrawal has already been processed by the L2 exchange. * * @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE. * @param assetType The exchange asset ID for the asset to withdraw. * * @return The ERC20 token amount received by this contract. */ function withdrawFromExchange( uint256 starkKey, uint256 assetType ) external nonReentrant onlyRole(EXCHANGE_OPERATOR_ROLE) onlyAllowedKey(starkKey) returns (uint256) { return _withdrawFromExchange(starkKey, assetType, false); } // ============ Internal Functions ============ function _withdrawFromExchange( uint256 starkKey, uint256 assetType, bool isGuardianAction ) internal returns (uint256) { uint256 startingBalance = getTokenBalance(); STARK_PERPETUAL.withdraw(starkKey, assetType); uint256 endingBalance = getTokenBalance(); uint256 tokenAmount = endingBalance.sub(startingBalance); emit WithdrewFromExchange(starkKey, assetType, tokenAmount, isGuardianAction); return tokenAmount; } function _forcedWithdrawalRequest( uint256 starkKey, uint256 vaultId, uint256 quantizedAmount, bool premiumCost, bool isGuardianAction ) internal { STARK_PERPETUAL.forcedWithdrawalRequest(starkKey, vaultId, quantizedAmount, premiumCost); emit RequestedForcedWithdrawal(starkKey, vaultId, isGuardianAction); } function _forcedTradeRequest( uint256[12] calldata args, bytes calldata signature, bool isGuardianAction ) internal { // Split into two functions to avoid error 'call stack too deep'. if (args[11] != 0) { _forcedTradeRequestPremiumCostTrue(args, signature); } else { _forcedTradeRequestPremiumCostFalse(args, signature); } emit RequestedForcedTrade( args[0], // starkKeyA args[2], // vaultIdA isGuardianAction ); } // ============ Private Functions ============ // Split into two functions to avoid error 'call stack too deep'. function _forcedTradeRequestPremiumCostTrue( uint256[12] calldata args, bytes calldata signature ) private { STARK_PERPETUAL.forcedTradeRequest( args[0], // starkKeyA args[1], // starkKeyB args[2], // vaultIdA args[3], // vaultIdB args[4], // collateralAssetId args[5], // syntheticAssetId args[6], // amountCollateral args[7], // amountSynthetic args[8] != 0, // aIsBuyingSynthetic args[9], // submissionExpirationTime args[10], // nonce signature, true // premiumCost ); } // Split into two functions to avoid error 'call stack too deep'. function _forcedTradeRequestPremiumCostFalse( uint256[12] calldata args, bytes calldata signature ) private { STARK_PERPETUAL.forcedTradeRequest( args[0], // starkKeyA args[1], // starkKeyB args[2], // vaultIdA args[3], // vaultIdB args[4], // collateralAssetId args[5], // syntheticAssetId args[6], // amountCollateral args[7], // amountSynthetic args[8] != 0, // aIsBuyingSynthetic args[9], // submissionExpirationTime args[10], // nonce signature, false // premiumCost ); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol'; import { Math } from '../../../utils/Math.sol'; import { SP1Roles } from './SP1Roles.sol'; /** * @title SP1Balances * @author dYdX * * @dev Contains common constants and functions related to token balances. */ abstract contract SP1Balances is SP1Roles { using SafeMath for uint256; // ============ Constants ============ IERC20 public immutable TOKEN; ILiquidityStakingV1 public immutable LIQUIDITY_STAKING; // ============ Constructor ============ constructor( ILiquidityStakingV1 liquidityStaking, IERC20 token ) { LIQUIDITY_STAKING = liquidityStaking; TOKEN = token; } // ============ Public Functions ============ function getAllocatedBalanceCurrentEpoch() public view returns (uint256) { return LIQUIDITY_STAKING.getAllocatedBalanceCurrentEpoch(address(this)); } function getAllocatedBalanceNextEpoch() public view returns (uint256) { return LIQUIDITY_STAKING.getAllocatedBalanceNextEpoch(address(this)); } function getBorrowableAmount() public view returns (uint256) { if (_IS_BORROWING_RESTRICTED_) { return 0; } return LIQUIDITY_STAKING.getBorrowableAmount(address(this)); } function getBorrowedBalance() public view returns (uint256) { return LIQUIDITY_STAKING.getBorrowedBalance(address(this)); } function getDebtBalance() public view returns (uint256) { return LIQUIDITY_STAKING.getBorrowerDebtBalance(address(this)); } function getBorrowedAndDebtBalance() public view returns (uint256) { return getBorrowedBalance().add(getDebtBalance()); } function getTokenBalance() public view returns (uint256) { return TOKEN.balanceOf(address(this)); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SP1Storage } from './SP1Storage.sol'; /** * @title SP1Roles * @author dYdX * * @dev Defines roles used in the StarkProxyV1 contract. The hierarchy and powers of each role * are described below. Not all roles need to be used. * * Overview: * * During operation of this contract, funds will flow between the following three * contracts: * * LiquidityStaking <> StarkProxy <> StarkPerpetual * * Actions which move fund from left to right are called “open” actions, whereas actions which * move funds from right to left are called “close” actions. * * Also note that the “forced” actions (forced trade and forced withdrawal) require special care * since they directly impact the financial risk of positions held on the exchange. * * Roles: * * GUARDIAN_ROLE * | -> May perform “close” actions as defined above, but “forced” actions can only be taken * | if the borrower has an outstanding debt balance. * | -> May restrict “open” actions as defined above, except w.r.t. funds in excess of the * | borrowed balance. * | -> May approve a token amount to be withdrawn externally by the WITHDRAWAL_OPERATOR_ROLE * | to an allowed address. * | * +-- VETO_GUARDIAN_ROLE * -> May veto forced trade requests initiated by the owner, during the waiting period. * * OWNER_ROLE * | -> May add or remove allowed recipients who may receive excess funds. * | -> May add or remove allowed STARK keys for use on the exchange. * | -> May set ERC20 allowances on the LiquidityStakingV1 and StarkPerpetual contracts. * | -> May call the “forced” actions: forcedWithdrawalRequest and forcedTradeRequest. * | * +-- DELEGATION_ADMIN_ROLE * | * +-- BORROWER_ROLE * | -> May call functions on LiquidityStakingV1: autoPayOrBorrow, borrow, repay, * | and repayDebt. * | * +-- EXCHANGE_OPERATOR_ROLE * | -> May call functions on StarkPerpetual: depositToExchange and * | withdrawFromExchange. * | * +-- WITHDRAWAL_OPERATOR_ROLE * -> May withdraw funds in excess of the borrowed balance to an allowed recipient. */ abstract contract SP1Roles is SP1Storage { bytes32 public constant GUARDIAN_ROLE = keccak256('GUARDIAN_ROLE'); bytes32 public constant VETO_GUARDIAN_ROLE = keccak256('VETO_GUARDIAN_ROLE'); bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant DELEGATION_ADMIN_ROLE = keccak256('DELEGATION_ADMIN_ROLE'); bytes32 public constant BORROWER_ROLE = keccak256('BORROWER_ROLE'); bytes32 public constant EXCHANGE_OPERATOR_ROLE = keccak256('EXCHANGE_OPERATOR_ROLE'); bytes32 public constant WITHDRAWAL_OPERATOR_ROLE = keccak256('WITHDRAWAL_OPERATOR_ROLE'); function __SP1Roles_init( address guardian ) internal { // Assign GUARDIAN_ROLE. _setupRole(GUARDIAN_ROLE, guardian); // Assign OWNER_ROLE and DELEGATION_ADMIN_ROLE to the sender. _setupRole(OWNER_ROLE, msg.sender); _setupRole(DELEGATION_ADMIN_ROLE, msg.sender); // Set admins for all roles. (Don't use the default admin role.) _setRoleAdmin(GUARDIAN_ROLE, GUARDIAN_ROLE); _setRoleAdmin(VETO_GUARDIAN_ROLE, GUARDIAN_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(DELEGATION_ADMIN_ROLE, OWNER_ROLE); _setRoleAdmin(BORROWER_ROLE, DELEGATION_ADMIN_ROLE); _setRoleAdmin(EXCHANGE_OPERATOR_ROLE, DELEGATION_ADMIN_ROLE); _setRoleAdmin(WITHDRAWAL_OPERATOR_ROLE, DELEGATION_ADMIN_ROLE); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol'; import { Math } from '../../../utils/Math.sol'; import { SP1Balances } from './SP1Balances.sol'; /** * @title SP1Borrowing * @author dYdX * * @dev Handles calls to the LiquidityStaking contract to borrow and repay funds. */ abstract contract SP1Borrowing is SP1Balances { using SafeMath for uint256; // ============ Events ============ event Borrowed( uint256 amount, uint256 newBorrowedBalance ); event RepaidBorrow( uint256 amount, uint256 newBorrowedBalance, bool isGuardianAction ); event RepaidDebt( uint256 amount, uint256 newDebtBalance, bool isGuardianAction ); // ============ Constructor ============ constructor( ILiquidityStakingV1 liquidityStaking, IERC20 token ) SP1Balances(liquidityStaking, token) {} // ============ External Functions ============ /** * @notice Automatically repay or borrow to bring borrowed balance to the next allocated balance. * Must be called during the blackout window, to ensure allocated balance will not change before * the start of the next epoch. Reverts if there are insufficient funds to prevent a shortfall. * * Can be called with eth_call to view amounts that will be borrowed or repaid. * * @return The newly borrowed amount. * @return The borrow amount repaid. * @return The debt amount repaid. */ function autoPayOrBorrow() external nonReentrant onlyRole(BORROWER_ROLE) returns ( uint256, uint256, uint256 ) { // Ensure we are in the blackout window. require( LIQUIDITY_STAKING.inBlackoutWindow(), 'SP1Borrowing: Auto-pay may only be used during the blackout window' ); // Get the borrowed balance, next allocated balance, and token balance. uint256 borrowedBalance = getBorrowedBalance(); uint256 nextAllocatedBalance = getAllocatedBalanceNextEpoch(); uint256 tokenBalance = getTokenBalance(); // Return values. uint256 borrowAmount = 0; uint256 repayBorrowAmount = 0; uint256 repayDebtAmount = 0; if (borrowedBalance > nextAllocatedBalance) { // Make the necessary repayment due by the end of the current epoch. repayBorrowAmount = borrowedBalance.sub(nextAllocatedBalance); require( tokenBalance >= repayBorrowAmount, 'SP1Borrowing: Insufficient funds to avoid falling short on repayment' ); _repayBorrow(repayBorrowAmount, false); } else { // Borrow the max borrowable amount. borrowAmount = getBorrowableAmount(); if (borrowAmount != 0) { _borrow(borrowAmount); } } // Finally, use remaining funds to pay any overdue debt. uint256 debtBalance = getDebtBalance(); repayDebtAmount = Math.min(debtBalance, tokenBalance); if (repayDebtAmount != 0) { _repayDebt(repayDebtAmount, false); } return (borrowAmount, repayBorrowAmount, repayDebtAmount); } function borrow( uint256 amount ) external nonReentrant onlyRole(BORROWER_ROLE) { // Disallow if the guardian has restricted borrowing. require( !_IS_BORROWING_RESTRICTED_, 'SP1Borrowing: Cannot borrow while Restricted' ); _borrow(amount); } function repayBorrow( uint256 amount ) external nonReentrant onlyRole(BORROWER_ROLE) { _repayBorrow(amount, false); } function repayDebt( uint256 amount ) external nonReentrant onlyRole(BORROWER_ROLE) { _repayDebt(amount, false); } // ============ Internal Functions ============ function _borrow( uint256 amount ) internal { LIQUIDITY_STAKING.borrow(amount); emit Borrowed(amount, getBorrowedBalance()); } function _repayBorrow( uint256 amount, bool isGovernanceAction ) internal { LIQUIDITY_STAKING.repayBorrow(address(this), amount); emit RepaidBorrow(amount, getBorrowedBalance(), isGovernanceAction); } function _repayDebt( uint256 amount, bool isGovernanceAction ) internal { LIQUIDITY_STAKING.repayDebt(address(this), amount); emit RepaidDebt(amount, getDebtBalance(), isGovernanceAction); } }
Split into two functions to avoid error 'call stack too deep'.
function _forcedTradeRequestPremiumCostFalse( uint256[12] calldata args, bytes calldata signature ) private { STARK_PERPETUAL.forcedTradeRequest( signature, ); }
221,924
./full_match/4/0xf281aB231B0B2C43336075e6546fd642359Ac4e0/sources/browser/SellToken.sol
withDraw token by milestone 30/25/25/20 % sent transfer to sender sent fee to dev
function withDrawToken(uint256 _orderId, uint256 _milestone) public { Order storage order = orders[_orderId]; uint256 rewardPending = 0; uint256 feePending = 0; bool isWithDraw = false; uint256 milestone = 0; if (_milestone == 30 && order.timestampLastWithDraw==0) { milestone=30; isWithDraw = true; order.t1 = true; } if (order.t2 != true && _milestone == 251) { milestone=25; isWithDraw = true; order.t2 = true; } if (order.t3 != true && _milestone == 252) { milestone=25; isWithDraw = true; order.t3 = true; } if (order.t4 != true && _milestone == 20) { milestone=20; isWithDraw = true; order.t4 = true; } if (isWithDraw) { rewardPending = getRewardByPercent(_orderId, milestone); order.rewarded = order.rewarded.add(rewardPending); order.timestampLastWithDraw = block.timestamp; sendTransferReward(msg.sender, rewardPending.sub(feePending)); sendTransferReward(dev_adress, feePending); User storage user = users[order.userId]; user.totalJUS = user.totalJUS.add(rewardPending); if(rewardPending>0){ user.totalJUSBlock = user.totalJUSBlock.sub(rewardPending); } } }
645,518
./partial_match/1/0xC58212BD2cC5D60Cb89E980713461Be027389b2C/sources/RPDFoundersPass.sol
Set Total Tokens Supply/
function setTotalTokens(uint256 qty) public onlyOwner { TOTAL_TOKENS = qty; }
3,988,639
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ abstract contract ERC20MetadataStorage is ERC20 { string private _name; string private _symbol; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public virtual view returns(string memory) { return _name; } /** * @dev Returns the symbol of the token. */ function symbol() public virtual view returns(string memory) { return _symbol; } }
Returns the name of the token./
function name() public virtual view returns(string memory) { return _name; }
6,475,536
pragma solidity 0.5.17; import "../utils/ModUtils.sol"; /** * @title Operations on alt_bn128 * @dev Implementations of common elliptic curve operations on Ethereum's * (poorly named) alt_bn128 curve. Whenever possible, use post-Byzantium * pre-compiled contracts to offset gas costs. Note that these pre-compiles * might not be available on all (eg private) chains. */ library AltBn128 { using ModUtils for uint256; // G1Point implements a point in G1 group. struct G1Point { uint256 x; uint256 y; } // gfP2 implements a field of size p² as a quadratic extension of the base field. struct gfP2 { uint256 x; uint256 y; } // G2Point implements a point in G2 group. struct G2Point { gfP2 x; gfP2 y; } // p is a prime over which we form a basic field // Taken from go-ethereum/crypto/bn256/cloudflare/constants.go uint256 constant p = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function getP() internal pure returns (uint256) { return p; } /** * @dev Gets generator of G1 group. * Taken from go-ethereum/crypto/bn256/cloudflare/curve.go */ uint256 constant g1x = 1; uint256 constant g1y = 2; function g1() internal pure returns (G1Point memory) { return G1Point(g1x, g1y); } /** * @dev Gets generator of G2 group. * Taken from go-ethereum/crypto/bn256/cloudflare/twist.go */ uint256 constant g2xx = 11559732032986387107991004021392285783925812861821192530917403151452391805634; uint256 constant g2xy = 10857046999023057135944570762232829481370756359578518086990519993285655852781; uint256 constant g2yx = 4082367875863433681332203403145435568316851327593401208105741076214120093531; uint256 constant g2yy = 8495653923123431417604973247489272438418190587263600148770280649306958101930; function g2() internal pure returns (G2Point memory) { return G2Point(gfP2(g2xx, g2xy), gfP2(g2yx, g2yy)); } /** * @dev Gets twist curve B constant. * Taken from go-ethereum/crypto/bn256/cloudflare/twist.go */ uint256 constant twistBx = 266929791119991161246907387137283842545076965332900288569378510910307636690; uint256 constant twistBy = 19485874751759354771024239261021720505790618469301721065564631296452457478373; function twistB() private pure returns (gfP2 memory) { return gfP2(twistBx, twistBy); } /** * @dev Gets root of the point where x and y are equal. */ uint256 constant hexRootX = 21573744529824266246521972077326577680729363968861965890554801909984373949499; uint256 constant hexRootY = 16854739155576650954933913186877292401521110422362946064090026408937773542853; function hexRoot() private pure returns (gfP2 memory) { return gfP2(hexRootX, hexRootY); } /** * @dev g1YFromX computes a Y value for a G1 point based on an X value. * This computation is simply evaluating the curve equation for Y on a * given X, and allows a point on the curve to be represented by just * an X value + a sign bit. */ function g1YFromX(uint256 x) internal view returns (uint256) { return ((x.modExp(3, p) + 3) % p).modSqrt(p); } /** * @dev g2YFromX computes a Y value for a G2 point based on an X value. * This computation is simply evaluating the curve equation for Y on a * given X, and allows a point on the curve to be represented by just * an X value + a sign bit. */ function g2YFromX(gfP2 memory _x) internal pure returns (gfP2 memory y) { (uint256 xx, uint256 xy) = _gfP2CubeAddTwistB(_x.x, _x.y); // Using formula y = x ^ (p^2 + 15) / 32 from // https://github.com/ethereum/beacon_chain/blob/master/beacon_chain/utils/bls.py // (p^2 + 15) / 32 results into a big 512bit value, so breaking it to two uint256 as (a * a + b) uint256 a = 3869331240733915743250440106392954448556483137451914450067252501901456824595; uint256 b = 146360017852723390495514512480590656176144969185739259173561346299185050597; (uint256 xbx, uint256 xby) = _gfP2Pow(xx, xy, b); (uint256 yax, uint256 yay) = _gfP2Pow(xx, xy, a); (uint256 ya2x, uint256 ya2y) = _gfP2Pow(yax, yay, a); (y.x, y.y) = _gfP2Multiply(ya2x, ya2y, xbx, xby); // Multiply y by hexRoot constant to find correct y. while (!_g2X2y(xx, xy, y.x, y.y)) { (y.x, y.y) = _gfP2Multiply(y.x, y.y, hexRootX, hexRootY); } } /** * @dev Hash a byte array message, m, and map it deterministically to a * point on G1. Note that this approach was chosen for its simplicity / * lower gas cost on the EVM, rather than good distribution of points on * G1. */ function g1HashToPoint(bytes memory m) internal view returns (G1Point memory) { bytes32 h = sha256(m); uint256 x = uint256(h) % p; uint256 y; while (true) { y = g1YFromX(x); if (y > 0) { return G1Point(x, y); } x += 1; } } /** * @dev Calculates whether the provided number is even or odd. * @return 0x01 if y is an even number and 0x00 if it's odd. */ function parity(uint256 value) private pure returns (bytes1) { return bytes32(value)[31] & 0x01; } /** * @dev Compress a point on G1 to a single uint256 for serialization. */ function g1Compress(G1Point memory point) internal pure returns (bytes32) { bytes32 m = bytes32(point.x); bytes1 leadM = m[0] | (parity(point.y) << 7); uint256 mask = 0xff << (31 * 8); m = (m & ~bytes32(mask)) | (leadM >> 0); return m; } /** * @dev Compress a point on G2 to a pair of uint256 for serialization. */ function g2Compress(G2Point memory point) internal pure returns (bytes memory) { bytes32 m = bytes32(point.x.x); bytes1 leadM = m[0] | (parity(point.y.x) << 7); uint256 mask = 0xff << (31 * 8); m = (m & ~bytes32(mask)) | (leadM >> 0); return abi.encodePacked(m, bytes32(point.x.y)); } /** * @dev Decompress a point on G1 from a single uint256. */ function g1Decompress(bytes32 m) internal view returns (G1Point memory) { bytes32 mX = bytes32(0); bytes1 leadX = m[0] & 0x7f; uint256 mask = 0xff << (31 * 8); mX = (m & ~bytes32(mask)) | (leadX >> 0); uint256 x = uint256(mX); uint256 y = g1YFromX(x); if (parity(y) != (m[0] & 0x80) >> 7) { y = p - y; } require(isG1PointOnCurve(G1Point(x, y)), "Malformed bn256.G1 point."); return G1Point(x, y); } /** * @dev Unmarshals a point on G1 from bytes in an uncompressed form. */ function g1Unmarshal(bytes memory m) internal pure returns (G1Point memory) { require(m.length == 64, "Invalid G1 bytes length"); bytes32 x; bytes32 y; /* solium-disable-next-line */ assembly { x := mload(add(m, 0x20)) y := mload(add(m, 0x40)) } return G1Point(uint256(x), uint256(y)); } /** * @dev Marshals a point on G1 to bytes form. */ function g1Marshal(G1Point memory point) internal pure returns (bytes memory) { bytes memory m = new bytes(64); bytes32 x = bytes32(point.x); bytes32 y = bytes32(point.y); /* solium-disable-next-line */ assembly { mstore(add(m, 32), x) mstore(add(m, 64), y) } return m; } /** * @dev Unmarshals a point on G2 from bytes in an uncompressed form. */ function g2Unmarshal(bytes memory m) internal pure returns (G2Point memory) { require(m.length == 128, "Invalid G2 bytes length"); uint256 xx; uint256 xy; uint256 yx; uint256 yy; /* solium-disable-next-line */ assembly { xx := mload(add(m, 0x20)) xy := mload(add(m, 0x40)) yx := mload(add(m, 0x60)) yy := mload(add(m, 0x80)) } return G2Point(gfP2(xx, xy), gfP2(yx, yy)); } /** * @dev Decompress a point on G2 from a pair of uint256. */ function g2Decompress(bytes memory m) internal pure returns (G2Point memory) { require(m.length == 64, "Invalid G2 compressed bytes length"); bytes32 x1; bytes32 x2; uint256 temp; // Extract two bytes32 from bytes array /* solium-disable-next-line */ assembly { temp := add(m, 32) x1 := mload(temp) temp := add(m, 64) x2 := mload(temp) } bytes32 mX = bytes32(0); bytes1 leadX = x1[0] & 0x7f; uint256 mask = 0xff << (31 * 8); mX = (x1 & ~bytes32(mask)) | (leadX >> 0); gfP2 memory x = gfP2(uint256(mX), uint256(x2)); gfP2 memory y = g2YFromX(x); if (parity(y.x) != (m[0] & 0x80) >> 7) { y.x = p - y.x; y.y = p - y.y; } return G2Point(x, y); } /** * @dev Wrap the point addition pre-compile introduced in Byzantium. Return * the sum of two points on G1. Revert if the provided points aren't on the * curve. */ function g1Add(G1Point memory a, G1Point memory b) internal view returns (G1Point memory c) { /* solium-disable-next-line */ assembly { let arg := mload(0x40) mstore(arg, mload(a)) mstore(add(arg, 0x20), mload(add(a, 0x20))) mstore(add(arg, 0x40), mload(b)) mstore(add(arg, 0x60), mload(add(b, 0x20))) // 0x60 is the ECADD precompile address if iszero(staticcall(not(0), 0x06, arg, 0x80, c, 0x40)) { revert(0, 0) } } } /** * @dev Return the sum of two gfP2 field elements. */ function gfP2Add(gfP2 memory a, gfP2 memory b) internal pure returns (gfP2 memory) { return gfP2(addmod(a.x, b.x, p), addmod(a.y, b.y, p)); } /** * @dev Return multiplication of two gfP2 field elements. */ function gfP2Multiply(gfP2 memory a, gfP2 memory b) internal pure returns (gfP2 memory) { return gfP2( addmod(mulmod(a.x, b.y, p), mulmod(b.x, a.y, p), p), addmod(mulmod(a.y, b.y, p), p - mulmod(a.x, b.x, p), p) ); } /** * @dev Return gfP2 element to the power of the provided exponent. */ function gfP2Pow(gfP2 memory _a, uint256 _exp) internal pure returns (gfP2 memory result) { (uint256 x, uint256 y) = _gfP2Pow(_a.x, _a.y, _exp); return gfP2(x, y); } function gfP2Square(gfP2 memory a) internal pure returns (gfP2 memory) { return gfP2Multiply(a, a); } function gfP2Cube(gfP2 memory a) internal pure returns (gfP2 memory) { return gfP2Multiply(a, gfP2Square(a)); } function gfP2CubeAddTwistB(gfP2 memory a) internal pure returns (gfP2 memory) { (uint256 x, uint256 y) = _gfP2CubeAddTwistB(a.x, a.y); return gfP2(x, y); } /** * @dev Return true if G2 point's y^2 equals x. */ function g2X2y(gfP2 memory x, gfP2 memory y) internal pure returns (bool) { gfP2 memory y2; y2 = gfP2Square(y); return (y2.x == x.x && y2.y == x.y); } /** * @dev Return true if G1 point is on the curve. */ function isG1PointOnCurve(G1Point memory point) internal view returns (bool) { return point.y.modExp(2, p) == (point.x.modExp(3, p) + 3) % p; } /** * @dev Return true if G2 point is on the curve. */ function isG2PointOnCurve(G2Point memory point) internal pure returns (bool) { (uint256 y2x, uint256 y2y) = _gfP2Square(point.y.x, point.y.y); (uint256 x3x, uint256 x3y) = _gfP2CubeAddTwistB(point.x.x, point.x.y); return (y2x == x3x && y2y == x3y); } /** * @dev Wrap the scalar point multiplication pre-compile introduced in * Byzantium. The result of a point from G1 multiplied by a scalar should * match the point added to itself the same number of times. Revert if the * provided point isn't on the curve. */ function scalarMultiply(G1Point memory p_1, uint256 scalar) internal view returns (G1Point memory p_2) { assembly { let arg := mload(0x40) mstore(arg, mload(p_1)) mstore(add(arg, 0x20), mload(add(p_1, 0x20))) mstore(add(arg, 0x40), scalar) // 0x07 is the ECMUL precompile address if iszero(staticcall(not(0), 0x07, arg, 0x60, p_2, 0x40)) { revert(0, 0) } } } /** * @dev Wrap the pairing check pre-compile introduced in Byzantium. Return * the result of a pairing check of 2 pairs (G1 p1, G2 p2) (G1 p3, G2 p4) */ function pairing( G1Point memory p1, G2Point memory p2, G1Point memory p3, G2Point memory p4 ) internal view returns (bool result) { uint256 _c; /* solium-disable-next-line */ assembly { let c := mload(0x40) let arg := add(c, 0x20) mstore(arg, mload(p1)) mstore(add(arg, 0x20), mload(add(p1, 0x20))) let p2x := mload(p2) mstore(add(arg, 0x40), mload(p2x)) mstore(add(arg, 0x60), mload(add(p2x, 0x20))) let p2y := mload(add(p2, 0x20)) mstore(add(arg, 0x80), mload(p2y)) mstore(add(arg, 0xa0), mload(add(p2y, 0x20))) mstore(add(arg, 0xc0), mload(p3)) mstore(add(arg, 0xe0), mload(add(p3, 0x20))) let p4x := mload(p4) mstore(add(arg, 0x100), mload(p4x)) mstore(add(arg, 0x120), mload(add(p4x, 0x20))) let p4y := mload(add(p4, 0x20)) mstore(add(arg, 0x140), mload(p4y)) mstore(add(arg, 0x160), mload(add(p4y, 0x20))) // call(gasLimit, to, value, inputOffset, inputSize, outputOffset, outputSize) if iszero(staticcall(not(0), 0x08, arg, 0x180, c, 0x20)) { revert(0, 0) } _c := mload(c) } return _c != 0; } function _gfP2Add( uint256 ax, uint256 ay, uint256 bx, uint256 by ) private pure returns (uint256 x, uint256 y) { x = addmod(ax, bx, p); y = addmod(ay, by, p); } function _gfP2Multiply( uint256 ax, uint256 ay, uint256 bx, uint256 by ) private pure returns (uint256 x, uint256 y) { x = addmod(mulmod(ax, by, p), mulmod(bx, ay, p), p); y = addmod(mulmod(ay, by, p), p - mulmod(ax, bx, p), p); } function _gfP2CubeAddTwistB(uint256 ax, uint256 ay) private pure returns (uint256 x, uint256 y) { (uint256 a3x, uint256 a3y) = _gfP2Cube(ax, ay); return _gfP2Add(a3x, a3y, twistBx, twistBy); } function _gfP2Pow( uint256 _ax, uint256 _ay, uint256 _exp ) private pure returns (uint256 x, uint256 y) { uint256 exp = _exp; x = 0; y = 1; uint256 ax = _ax; uint256 ay = _ay; // Reduce exp dividing by 2 gradually to 0 while computing final // result only when exp is an odd number. while (exp > 0) { if (parity(exp) == 0x01) { (x, y) = _gfP2Multiply(x, y, ax, ay); } exp = exp / 2; (ax, ay) = _gfP2Multiply(ax, ay, ax, ay); } } function _gfP2Square(uint256 _ax, uint256 _ay) private pure returns (uint256 x, uint256 y) { return _gfP2Multiply(_ax, _ay, _ax, _ay); } function _gfP2Cube(uint256 _ax, uint256 _ay) private pure returns (uint256 x, uint256 y) { (uint256 _bx, uint256 _by) = _gfP2Square(_ax, _ay); return _gfP2Multiply(_ax, _ay, _bx, _by); } function _g2X2y( uint256 xx, uint256 xy, uint256 yx, uint256 yy ) private pure returns (bool) { (uint256 y2x, uint256 y2y) = _gfP2Square(yx, yy); return (y2x == xx && y2y == xy); } }
Return multiplication of two gfP2 field elements./
function gfP2Multiply(gfP2 memory a, gfP2 memory b) internal pure returns (gfP2 memory) { return gfP2( addmod(mulmod(a.x, b.y, p), mulmod(b.x, a.y, p), p), addmod(mulmod(a.y, b.y, p), p - mulmod(a.x, b.x, p), p) ); }
1,763,182
// Beta Job on the Keep4r.Network 🚀 // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } } // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) /** * @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 addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(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 multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(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; } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } interface IKeep4rV1 { function isKeeper(address) external returns (bool); function worked(address keeper) external; } // sliding oracle that uses observations collected to provide moving price averages in the past contract UniswapV2Oracle { using FixedPoint for *; using SafeMath for uint; struct Observation { uint timestamp; uint price0Cumulative; uint price1Cumulative; } modifier keeper() { require(KP4R.isKeeper(msg.sender), "::isKeeper: keeper is not registered"); _; } modifier upkeep() { require(KP4R.isKeeper(msg.sender), "::isKeeper: keeper is not registered"); _; KP4R.worked(msg.sender); } address public governance; address public pendingGovernance; /** * @notice Allows governance to change governance (for future upgradability) * @param _governance new governance address to set */ function setGovernance(address _governance) external { require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } /** * @notice Allows pendingGovernance to accept their role as governance (protection pattern) */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } IKeep4rV1 public constant KP4R = IKeep4rV1(0x6921B6A7bD3f39dEE1f883f3C4FCb35B2dFabbbA); address public constant factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; // this is redundant with granularity and windowSize, but stored for gas savings & informational purposes. uint public constant periodSize = 1800; address[] internal _pairs; mapping(address => bool) internal _known; function pairs() external view returns (address[] memory) { return _pairs; } // mapping from pair address to a list of price observations of that pair mapping(address => Observation[]) public pairObservations; constructor() public { governance = msg.sender; } function updatePair(address pair) external keeper returns (bool) { return _update(pair); } function update(address tokenA, address tokenB) external keeper returns (bool) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); return _update(pair); } function add(address tokenA, address tokenB) external { require(msg.sender == governance, "UniswapV2Oracle::add: !gov"); address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); require(!_known[pair], "known"); _known[pair] = true; _pairs.push(pair); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); pairObservations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); } function work() public upkeep { bool worked = _updateAll(); require(worked, "UniswapV2Oracle: !work"); } function workForFree() public keeper { bool worked = _updateAll(); require(worked, "UniswapV2Oracle: !work"); } function lastObservation(address pair) public view returns (Observation memory) { return pairObservations[pair][pairObservations[pair].length-1]; } function _updateAll() internal returns (bool updated) { for (uint i = 0; i < _pairs.length; i++) { if (_update(_pairs[i])) { updated = true; } } } function updateFor(uint i, uint length) external keeper returns (bool updated) { for (; i < length; i++) { if (_update(_pairs[i])) { updated = true; } } } function workable(address pair) public view returns (bool) { return (block.timestamp - lastObservation(pair).timestamp) > periodSize; } function workable() external view returns (bool) { for (uint i = 0; i < _pairs.length; i++) { if (workable(_pairs[i])) { return true; } } return false; } function _update(address pair) internal returns (bool) { // we only want to commit updates once per period (i.e. windowSize / granularity) uint timeElapsed = block.timestamp - lastObservation(pair).timestamp; if (timeElapsed > periodSize) { (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); pairObservations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); return true; } return false; } function computeAmountOut( uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn ) private pure returns (uint amountOut) { // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.mul(amountIn).decode144(); } function _valid(address pair, uint age) internal view returns (bool) { return (block.timestamp - lastObservation(pair).timestamp) <= age; } function current(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) { address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut); require(_valid(pair, periodSize.mul(2)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.sortTokens(tokenIn, tokenOut); Observation memory _observation = lastObservation(pair); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); if (block.timestamp == _observation.timestamp) { _observation = pairObservations[pair][pairObservations[pair].length-2]; } uint timeElapsed = block.timestamp - _observation.timestamp; timeElapsed = timeElapsed == 0 ? 1 : timeElapsed; if (token0 == tokenIn) { return computeAmountOut(_observation.price0Cumulative, price0Cumulative, timeElapsed, amountIn); } else { return computeAmountOut(_observation.price1Cumulative, price1Cumulative, timeElapsed, amountIn); } } function quote(address tokenIn, uint amountIn, address tokenOut, uint granularity) external view returns (uint amountOut) { address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut); require(_valid(pair, periodSize.mul(granularity)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.sortTokens(tokenIn, tokenOut); uint priceAverageCumulative = 0; uint length = pairObservations[pair].length-1; uint i = length.sub(granularity); uint nextIndex = 0; if (token0 == tokenIn) { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += computeAmountOut( pairObservations[pair][i].price0Cumulative, pairObservations[pair][nextIndex].price0Cumulative, pairObservations[pair][nextIndex].timestamp - pairObservations[pair][i].timestamp, amountIn); } } else { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += computeAmountOut( pairObservations[pair][i].price1Cumulative, pairObservations[pair][nextIndex].price1Cumulative, pairObservations[pair][nextIndex].timestamp - pairObservations[pair][i].timestamp, amountIn); } } return priceAverageCumulative.div(granularity); } }
Allows pendingGovernance to accept their role as governance (protection pattern)/
function acceptGovernance() external { require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } IKeep4rV1 public constant KP4R = IKeep4rV1(0x6921B6A7bD3f39dEE1f883f3C4FCb35B2dFabbbA); address public constant factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address[] internal _pairs; mapping(address => bool) internal _known;
2,338,971
./partial_match/1/0x01cF6B5684C7D9d0BbBd57a385e5F2B06D42771f/sources/Frame.sol
this is used on the dashboard to calculate the pending shards
function calculateTotalPendingShards(uint256[] memory tokens) public view returns(uint256) { uint256 possibleShards = 0; for (uint256 x = 0;x < tokens.length;x++) { uint256 _token = tokens[x]; possibleShards += shards.determineYield(tokenYield[_token]); delete _token; } return possibleShards; }
16,050,524
// SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol"; import "./interfaces/IxTrippyToken.sol"; import "./interfaces/ITrippyNFTStaking.sol"; contract TrippyNFTStaking is ITrippyNFTStaking, OwnableUpgradeable, PausableUpgradeable { using SafeMathUpgradeable for uint256; mapping(address => UserInfo) public userInfo; IERC721Enumerable public trippyNFT; IxTrippyToken public trippyToken; uint256 public lastUpdateBlock; uint256 public rewardPerBlock; uint256 public totalHashes; uint256 public accTrippyNFTPerShare; uint256 constant ACC_TRIPPY_PRECISION = 1e12; uint256 public ownerFee = 1000; // 10% address public ownerFeeReceiver; uint256 public daoFee = 2500; // 25% address public daoFeeReceiver; uint256 public communityFee = 1500; // 15% address public communityFeeReceiver; modifier updateRewardPool() { if (totalHashes > 0) { uint256 reward = _calculateReward(); accTrippyNFTPerShare = accTrippyNFTPerShare.add( reward.mul(ACC_TRIPPY_PRECISION).div(totalHashes) ); } lastUpdateBlock = block.number; _; } function initialize( address _trippyNFT, address _trippy, uint256 _rewardPerBlock, address _ownerFeeReceiver, address _daoFeeReceiver, address _communityFeeReceiver ) external initializer { __Ownable_init(); trippyNFT = IERC721Enumerable(_trippyNFT); trippyToken = IxTrippyToken(_trippy); rewardPerBlock = _rewardPerBlock; ownerFeeReceiver = _ownerFeeReceiver; daoFeeReceiver = _daoFeeReceiver; communityFeeReceiver = _communityFeeReceiver; } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } function setOwnerFee(uint256 _ownerFee) external onlyOwner { ownerFee = _ownerFee; } function setOwnerFeeReceiver(address _ownerFeeReceiver) external onlyOwner { ownerFeeReceiver = _ownerFeeReceiver; } function setDAOFee(uint256 _daoFee) external onlyOwner { daoFee = _daoFee; } function setDAOFeeReceiver(address _daoFeeReceiver) external onlyOwner { daoFeeReceiver = _daoFeeReceiver; } function setCommunityFee(uint256 _communityFee) external onlyOwner { communityFee = _communityFee; } function setCommunityFeeReceiver(address _communityFeeReceiver) external onlyOwner { communityFeeReceiver = _communityFeeReceiver; } function stake(uint256 _nftId) public override updateRewardPool whenNotPaused { require(_nftId > 0, "Staking: Nft id must be greater than 0"); UserInfo storage user = userInfo[_msgSender()]; // Calculate Fee & Reward ( uint256 feeToOwner, uint256 feeToDAO, uint256 feeToCommunity, uint256 rewardToUser ) = _calculateRewardOfUser(user); // Distribute the TrippyToken if (feeToOwner > 0) { trippyToken.mint(ownerFeeReceiver, feeToOwner); } if (feeToDAO > 0) { trippyToken.mint(daoFeeReceiver, feeToDAO); } if (feeToCommunity > 0) { trippyToken.mint(communityFeeReceiver, feeToCommunity); } if (rewardToUser > 0) { trippyToken.mint(_msgSender(), rewardToUser); } // Transfer NFT trippyNFT.transferFrom(_msgSender(), address(this), _nftId); totalHashes = totalHashes.add(1); // Update User Info user.hashes = user.hashes.add(1); user.rewardDebt = user.hashes.mul(accTrippyNFTPerShare).div( ACC_TRIPPY_PRECISION ); user.isStaked[_nftId] = true; emit StakedTrippyNFT(_nftId, address(this)); } function stakeMultiple(uint256[] memory _nftIds) external { uint256 length = _nftIds.length; for (uint256 i = 0; i < length; i++) { stake(_nftIds[i]); } } function withdraw(uint256 _nftId) public override updateRewardPool whenNotPaused { require(_nftId > 0, "Withdraw: Nft id must be greater than 0"); UserInfo storage user = userInfo[_msgSender()]; require(user.hashes > 0, "Withdraw: no NFTs to withdraw"); require(user.isStaked[_nftId], "Withdraw: didnt stake the NFT"); // Calculate Fee & Reward ( uint256 feeToOwner, uint256 feeToDAO, uint256 feeToCommunity, uint256 rewardToUser ) = _calculateRewardOfUser(user); // Distribute the TrippyToken if (feeToOwner > 0) { trippyToken.mint(ownerFeeReceiver, feeToOwner); } if (feeToDAO > 0) { trippyToken.mint(daoFeeReceiver, feeToDAO); } if (feeToCommunity > 0) { trippyToken.mint(communityFeeReceiver, feeToCommunity); } if (rewardToUser > 0) { trippyToken.mint(_msgSender(), rewardToUser); } // Transfer NFT trippyNFT.transferFrom(address(this), _msgSender(), _nftId); totalHashes = totalHashes.sub(1); // Update UserInfo user.hashes = user.hashes.sub(1); user.rewardDebt = user.hashes.mul(accTrippyNFTPerShare).div( ACC_TRIPPY_PRECISION ); user.isStaked[_nftId] = false; emit WithdrawnTrippyNFT(_nftId, _msgSender()); } function withdrawMultiple(uint256[] memory _nftIds) external { uint256 length = _nftIds.length; for (uint256 i = 0; i < length; i++) { withdraw(_nftIds[i]); } } function claim() external override updateRewardPool { UserInfo storage user = userInfo[_msgSender()]; require(user.hashes > 0, "Withdraw: no NFTs to withdraw"); // Calculate Fee & Reward ( uint256 feeToOwner, uint256 feeToDAO, uint256 feeToCommunity, uint256 rewardToUser ) = _calculateRewardOfUser(user); // Distribute the TrippyToken if (feeToOwner > 0) { trippyToken.mint(ownerFeeReceiver, feeToOwner); } if (feeToDAO > 0) { trippyToken.mint(daoFeeReceiver, feeToDAO); } if (feeToCommunity > 0) { trippyToken.mint(communityFeeReceiver, feeToCommunity); } if (rewardToUser > 0) { trippyToken.mint(_msgSender(), rewardToUser); emit ClaimTrippyNFT(rewardToUser, _msgSender()); } // Update UserInfo user.rewardDebt = user.hashes.mul(accTrippyNFTPerShare).div( ACC_TRIPPY_PRECISION ); } function setRewardPerBlock(uint256 _amount) external override onlyOwner { rewardPerBlock = _amount; } function calculateReward(address _owner) external view returns (uint256) { if (totalHashes > 0) { UserInfo storage user = userInfo[_owner]; uint256 reward = _calculateReward(); uint256 _accTrippyNFTPerShare = accTrippyNFTPerShare.add( reward.mul(ACC_TRIPPY_PRECISION).div(totalHashes) ); return user .hashes .mul(_accTrippyNFTPerShare) .div(ACC_TRIPPY_PRECISION) .sub(user.rewardDebt) .mul(1e4 - ownerFee - daoFee - communityFee) .div(1e4); } return 0; } function stakedTokensOfOwner(address _owner) external view returns (uint256[] memory) { UserInfo storage user = userInfo[_owner]; uint256[] memory nftIds = new uint256[](user.hashes); if (user.hashes > 0) { uint256 balance = trippyNFT.balanceOf(address(this)); uint256 j = 0; for (uint256 i = 0; i < balance; i++) { uint256 nftId = trippyNFT.tokenOfOwnerByIndex(address(this), i); if (user.isStaked[nftId]) { nftIds[j++] = nftId; } } } return nftIds; } function _calculateReward() internal view returns (uint256) { uint256 blocksPassed = block.number.sub(lastUpdateBlock); return rewardPerBlock.mul(blocksPassed); } function _calculateRewardOfUser(UserInfo storage user) internal view returns ( uint256 feeToOwner, uint256 feeToDAO, uint256 feeToCommunity, uint256 rewardToUser ) { uint256 pending = user .hashes .mul(accTrippyNFTPerShare) .div(ACC_TRIPPY_PRECISION) .sub(user.rewardDebt); feeToOwner = pending.mul(ownerFee).div(1e4); feeToDAO = pending.mul(daoFee).div(1e4); feeToCommunity = pending.mul(communityFee).div(1e4); rewardToUser = pending.sub(feeToOwner).sub(feeToDAO).sub( feeToCommunity ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal 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; } // 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.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // 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.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library 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.6.0 <0.8.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.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IxTrippyToken is IERC20 { function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface ITrippyNFTStaking { struct UserInfo { mapping(uint256 => bool) isStaked; uint256 rewardDebt; uint256 hashes; } event StakedTrippyNFT(uint256 nftId, address indexed recipient); event WithdrawnTrippyNFT(uint256 nftId, address indexed recipient); event ClaimTrippyNFT(uint256 pending, address indexed recipient); function stake(uint256 _nftId) external; function withdraw(uint256 _nftId) external; function claim() external; function setRewardPerBlock(uint256 _amount) external; }
Calculate Fee & Reward Distribute the TrippyToken
function stake(uint256 _nftId) public override updateRewardPool whenNotPaused { require(_nftId > 0, "Staking: Nft id must be greater than 0"); UserInfo storage user = userInfo[_msgSender()]; ( uint256 feeToOwner, uint256 feeToDAO, uint256 feeToCommunity, uint256 rewardToUser ) = _calculateRewardOfUser(user); if (feeToOwner > 0) { trippyToken.mint(ownerFeeReceiver, feeToOwner); } if (feeToDAO > 0) { trippyToken.mint(daoFeeReceiver, feeToDAO); } if (feeToCommunity > 0) { trippyToken.mint(communityFeeReceiver, feeToCommunity); } if (rewardToUser > 0) { trippyToken.mint(_msgSender(), rewardToUser); } totalHashes = totalHashes.add(1); user.rewardDebt = user.hashes.mul(accTrippyNFTPerShare).div( ACC_TRIPPY_PRECISION ); user.isStaked[_nftId] = true; emit StakedTrippyNFT(_nftId, address(this)); }
10,172,145
// Sources flattened with hardhat v2.8.4 https://hardhat.org // File @rari-capital/solmate/src/auth/[email protected] // SPDX-License-Identifier: GNU AGPLv3 pragma solidity >=0.8.0; /// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol) /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol) abstract contract Auth { event OwnerUpdated(address indexed user, address indexed newOwner); event AuthorityUpdated(address indexed user, Authority indexed newAuthority); address public owner; Authority public authority; constructor(address _owner, Authority _authority) { owner = _owner; authority = _authority; emit OwnerUpdated(msg.sender, _owner); emit AuthorityUpdated(msg.sender, _authority); } modifier requiresAuth() { require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED"); _; } function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) { Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas. // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be // aware that this makes protected functions uncallable even to the owner if the authority is out of order. return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner; } function setAuthority(Authority newAuthority) public virtual { // We check if the caller is the owner first because we want to ensure they can // always swap out the authority even if it's reverting or using up a lot of gas. require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig)); authority = newAuthority; emit AuthorityUpdated(msg.sender, newAuthority); } function setOwner(address newOwner) public virtual requiresAuth { owner = newOwner; emit OwnerUpdated(msg.sender, newOwner); } } /// @notice A generic interface for a contract which provides authorization data to an Auth instance. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol) /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol) interface Authority { function canCall( address user, address target, bytes4 functionSig ) external view returns (bool); } // File @rari-capital/solmate/src/tokens/[email protected] pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } } // File @rari-capital/solmate/src/utils/[email protected] pragma solidity >=0.8.0; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. library SafeTransferLib { /*/////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); } /*/////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument. mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 100 because the calldata length is 4 + 32 * 3. callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED"); } function safeTransfer( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED"); } function safeApprove( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED"); } /*/////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) { assembly { // Get how many bytes the call returned. let returnDataSize := returndatasize() // If the call reverted: if iszero(callStatus) { // Copy the revert message into memory. returndatacopy(0, 0, returnDataSize) // Revert with the same message. revert(0, returnDataSize) } switch returnDataSize case 32 { // Copy the return data into memory. returndatacopy(0, 0, returnDataSize) // Set success to whether it returned true. success := iszero(iszero(mload(0))) } case 0 { // There was no return data. success := 1 } default { // It returned some malformed input. success := 0 } } } } // File @rari-capital/solmate/src/tokens/[email protected] pragma solidity >=0.8.0; /// @notice Minimalist and modern Wrapped Ether implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/WETH.sol) /// @author Inspired by WETH9 (https://github.com/dapphub/ds-weth/blob/master/src/weth9.sol) contract WETH is ERC20("Wrapped Ether", "WETH", 18) { using SafeTransferLib for address; event Deposit(address indexed from, uint256 amount); event Withdrawal(address indexed to, uint256 amount); function deposit() public payable virtual { _mint(msg.sender, msg.value); emit Deposit(msg.sender, msg.value); } function withdraw(uint256 amount) public virtual { _burn(msg.sender, amount); emit Withdrawal(msg.sender, amount); msg.sender.safeTransferETH(amount); } receive() external payable virtual { deposit(); } } // File @rari-capital/solmate/src/utils/[email protected] pragma solidity >=0.8.0; /// @notice Safe unsigned integer casting library that reverts on overflow. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeCastLib.sol) /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol) library SafeCastLib { function safeCastTo248(uint256 x) internal pure returns (uint248 y) { require(x <= type(uint248).max); y = uint248(x); } function safeCastTo128(uint256 x) internal pure returns (uint128 y) { require(x <= type(uint128).max); y = uint128(x); } function safeCastTo96(uint256 x) internal pure returns (uint96 y) { require(x <= type(uint96).max); y = uint96(x); } function safeCastTo64(uint256 x) internal pure returns (uint64 y) { require(x <= type(uint64).max); y = uint64(x); } function safeCastTo32(uint256 x) internal pure returns (uint32 y) { require(x <= type(uint32).max); y = uint32(x); } } // File srcBuild/FixedPointMathLib.sol pragma solidity >=0.8.0; /// @notice Arithmetic library with operations for fixed-point numbers. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol) /// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol) library FixedPointMathLib { /* /////////////////////////////////////////////////////////////// SIMPLIFIED FIXED POINT OPERATIONS ////////////////////////////////////////////////////////////// */ uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s. function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down. } function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up. } function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down. } function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up. } /* /////////////////////////////////////////////////////////////// LOW LEVEL FIXED POINT OPERATIONS //////////////////////////////////////////////////////////////*/ function fmul( uint256 x, uint256 y, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(x == 0 || (x * y) / x == y) if iszero(or(iszero(x), eq(div(z, x), y))) { revert(0, 0) } // If baseUnit is zero this will return zero instead of reverting. z := div(z, baseUnit) } } function fdiv( uint256 x, uint256 y, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { // Store x * baseUnit in z for now. z := mul(x, baseUnit) // Equivalent to require(y != 0 && (x == 0 || (x * baseUnit) / x == baseUnit)) if iszero(and(iszero(iszero(y)), or(iszero(x), eq(div(z, x), baseUnit)))) { revert(0, 0) } // We ensure y is not zero above, so there is never division by zero here. z := div(z, y) } } function mulDivDown( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { revert(0, 0) } // Divide z by the denominator. z := div(z, denominator) } } function mulDivUp( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { revert(0, 0) } // First, divide z - 1 by the denominator and add 1. // Then multiply it by 0 if z is zero, or 1 otherwise. z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1)) } } function rpow( uint256 x, uint256 n, uint256 denominator ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { // 0 ** 0 = 1 z := denominator } default { // 0 ** n = 0 z := 0 } } default { switch mod(n, 2) case 0 { // If n is even, store denominator in z for now. z := denominator } default { // If n is odd, store x in z for now. z := x } // Shifting right by 1 is like dividing by 2. let half := shr(1, denominator) for { // Shift n right by 1 before looping to halve it. n := shr(1, n) } n { // Shift n right by 1 each iteration to halve it. n := shr(1, n) } { // Revert immediately if x ** 2 would overflow. // Equivalent to iszero(eq(div(xx, x), x)) here. if shr(128, x) { revert(0, 0) } // Store x squared. let xx := mul(x, x) // Round to the nearest number. let xxRound := add(xx, half) // Revert if xx + half overflowed. if lt(xxRound, xx) { revert(0, 0) } // Set x to scaled xxRound. x := div(xxRound, denominator) // If n is even: if mod(n, 2) { // Compute z * x. let zx := mul(z, x) // If z * x overflowed: if iszero(eq(div(zx, x), z)) { // Revert if x is non-zero. if iszero(iszero(x)) { revert(0, 0) } } // Round to the nearest number. let zxRound := add(zx, half) // Revert if zx + half overflowed. if lt(zxRound, zx) { revert(0, 0) } // Return properly scaled zxRound. z := div(zxRound, denominator) } } } } } /* /////////////////////////////////////////////////////////////// GENERAL NUMBER UTILITIES //////////////////////////////////////////////////////////////*/ function sqrt(uint256 x) internal pure returns (uint256 z) { assembly { // Start off with z at 1. z := 1 // Used below to help find a nearby power of 2. let y := x // Find the lowest power of 2 that is at least sqrt(x). if iszero(lt(y, 0x100000000000000000000000000000000)) { y := shr(128, y) // Like dividing by 2 ** 128. z := shl(64, z) } if iszero(lt(y, 0x10000000000000000)) { y := shr(64, y) // Like dividing by 2 ** 64. z := shl(32, z) } if iszero(lt(y, 0x100000000)) { y := shr(32, y) // Like dividing by 2 ** 32. z := shl(16, z) } if iszero(lt(y, 0x10000)) { y := shr(16, y) // Like dividing by 2 ** 16. z := shl(8, z) } if iszero(lt(y, 0x100)) { y := shr(8, y) // Like dividing by 2 ** 8. z := shl(4, z) } if iszero(lt(y, 0x10)) { y := shr(4, y) // Like dividing by 2 ** 4. z := shl(2, z) } if iszero(lt(y, 0x8)) { // Equivalent to 2 ** z. z := shl(1, z) } // Shifting right by 1 is like dividing by 2. z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) // Compute a rounded down version of z. let zRoundDown := div(x, z) // If zRoundDown is smaller, use it. if lt(zRoundDown, z) { z := zRoundDown } } } } // File srcBuild/interfaces/Strategy.sol pragma solidity ^0.8.11; /// @notice Minimal interface for Vault compatible strategies. /// @dev Designed for out of the box compatibility with Fuse cTokens. /// @dev Like cTokens, strategies must be transferrable ERC20s. abstract contract Strategy is ERC20 { /// @notice Returns whether the strategy accepts ETH or an ERC20. /// @return True if the strategy accepts ETH, false otherwise. /// @dev Only present in Fuse cTokens, not Compound cTokens. function isCEther() external view virtual returns (bool); /// @notice Withdraws a specific amount of underlying tokens from the strategy. /// @param amount The amount of underlying tokens to withdraw. /// @return An error code, or 0 if the withdrawal was successful. function redeemUnderlying(uint256 amount) external virtual returns (uint256); /// @notice Returns a user's strategy balance in underlying tokens. /// @param user The user to get the underlying balance of. /// @return The user's strategy balance in underlying tokens. /// @dev May mutate the state of the strategy by accruing interest. function balanceOfUnderlying(address user) external virtual returns (uint256); } /// @notice Minimal interface for Vault strategies that accept ERC20s. /// @dev Designed for out of the box compatibility with Fuse cERC20s. abstract contract ERC20Strategy is Strategy { /// @notice Returns the underlying ERC20 token the strategy accepts. /// @return The underlying ERC20 token the strategy accepts. function underlying() external view virtual returns (ERC20); /// @notice Deposit a specific amount of underlying tokens into the strategy. /// @param amount The amount of underlying tokens to deposit. /// @return An error code, or 0 if the deposit was successful. function mint(uint256 amount) external virtual returns (uint256); } /// @notice Minimal interface for Vault strategies that accept ETH. /// @dev Designed for out of the box compatibility with Fuse cEther. abstract contract ETHStrategy is Strategy { /// @notice Deposit a specific amount of ETH into the strategy. /// @dev The amount of ETH is specified via msg.value. Reverts on error. function mint() external payable virtual; } // File srcBuild/Vault.sol pragma solidity ^0.8.11; /// @title Aphra Vault (avToken) /// @author Transmissions11 and JetJadeja /// @notice Flexible, minimalist, and gas-optimized yield /// aggregator for earning interest on any ERC20 token. /// @notice changes from original are to rename Rari -> Aphra tokens and any usage of rvToken => avToken contract Vault is ERC20, Auth { using SafeCastLib for uint256; using SafeTransferLib for ERC20; using FixedPointMathLib for uint256; /* ////////////////////////////////////////////////////////////// CONSTANTS ///////////////////////////////////////////////////////////// */ /// @notice The maximum number of elements allowed on the withdrawal stack. /// @dev Needed to prevent denial of service attacks by queue operators. uint256 internal constant MAX_WITHDRAWAL_STACK_SIZE = 32; /* ////////////////////////////////////////////////////////////// IMMUTABLES ///////////////////////////////////////////////////////////// */ /// @notice The underlying token the Vault accepts. ERC20 public immutable UNDERLYING; /// @notice The base unit of the underlying token and hence avToken. /// @dev Equal to 10 ** decimals. Used for fixed point arithmetic. uint256 internal immutable BASE_UNIT; /// @notice Creates a new Vault that accepts a specific underlying token. /// @param _UNDERLYING The ERC20 compliant token the Vault should accept. constructor(ERC20 _UNDERLYING) ERC20( // ex:Aphra Vader Vault string(abi.encodePacked("Aphra ", _UNDERLYING.name(), " Vault")), // ex: avVader string(abi.encodePacked("av", _UNDERLYING.symbol())), // ex: 18 _UNDERLYING.decimals() ) Auth(Auth(msg.sender).owner(), Auth(msg.sender).authority()) { UNDERLYING = _UNDERLYING; BASE_UNIT = 10**decimals; // Prevent minting of avTokens until // the initialize function is called. totalSupply = type(uint256).max; } /* ////////////////////////////////////////////////////////////// FEE CONFIGURATION ///////////////////////////////////////////////////////////// */ /// @notice The percentage of profit recognized each harvest to reserve as fees. /// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%. uint256 public feePercent; /// @notice Emitted when the fee percentage is updated. /// @param user The authorized user who triggered the update. /// @param newFeePercent The new fee percentage. event FeePercentUpdated(address indexed user, uint256 newFeePercent); /// @notice Sets a new fee percentage. /// @param newFeePercent The new fee percentage. function setFeePercent(uint256 newFeePercent) external requiresAuth { // A fee percentage over 100% doesn't make sense. require(newFeePercent <= 1e18, "FEE_TOO_HIGH"); // Update the fee percentage. feePercent = newFeePercent; emit FeePercentUpdated(msg.sender, newFeePercent); } /* ////////////////////////////////////////////////////////////// HARVEST CONFIGURATION ///////////////////////////////////////////////////////////// */ /// @notice Emitted when the harvest window is updated. /// @param user The authorized user who triggered the update. /// @param newHarvestWindow The new harvest window. event HarvestWindowUpdated(address indexed user, uint128 newHarvestWindow); /// @notice Emitted when the harvest delay is updated. /// @param user The authorized user who triggered the update. /// @param newHarvestDelay The new harvest delay. event HarvestDelayUpdated(address indexed user, uint64 newHarvestDelay); /// @notice Emitted when the harvest delay is scheduled to be updated next harvest. /// @param user The authorized user who triggered the update. /// @param newHarvestDelay The scheduled updated harvest delay. event HarvestDelayUpdateScheduled(address indexed user, uint64 newHarvestDelay); /// @notice The period in seconds during which multiple harvests can occur /// regardless if they are taking place before the harvest delay has elapsed. /// @dev Long harvest windows open the Vault up to profit distribution slowdown attacks. uint128 public harvestWindow; /// @notice The period in seconds over which locked profit is unlocked. /// @dev Cannot be 0 as it opens harvests up to sandwich attacks. uint64 public harvestDelay; /// @notice The value that will replace harvestDelay next harvest. /// @dev In the case that the next delay is 0, no update will be applied. uint64 public nextHarvestDelay; /// @notice Sets a new harvest window. /// @param newHarvestWindow The new harvest window. /// @dev The Vault's harvestDelay must already be set before calling. function setHarvestWindow(uint128 newHarvestWindow) external requiresAuth { // A harvest window longer than the harvest delay doesn't make sense. require(newHarvestWindow <= harvestDelay, "WINDOW_TOO_LONG"); // Update the harvest window. harvestWindow = newHarvestWindow; emit HarvestWindowUpdated(msg.sender, newHarvestWindow); } /// @notice Sets a new harvest delay. /// @param newHarvestDelay The new harvest delay to set. /// @dev If the current harvest delay is 0, meaning it has not /// been set before, it will be updated immediately, otherwise /// it will be scheduled to take effect after the next harvest. function setHarvestDelay(uint64 newHarvestDelay) external requiresAuth { // A harvest delay of 0 makes harvests vulnerable to sandwich attacks. require(newHarvestDelay != 0, "DELAY_CANNOT_BE_ZERO"); // A harvest delay longer than 1 year doesn't make sense. require(newHarvestDelay <= 365 days, "DELAY_TOO_LONG"); // If the harvest delay is 0, meaning it has not been set before: if (harvestDelay == 0) { // We'll apply the update immediately. harvestDelay = newHarvestDelay; emit HarvestDelayUpdated(msg.sender, newHarvestDelay); } else { // We'll apply the update next harvest. nextHarvestDelay = newHarvestDelay; emit HarvestDelayUpdateScheduled(msg.sender, newHarvestDelay); } } /* ////////////////////////////////////////////////////////////// TARGET FLOAT CONFIGURATION ///////////////////////////////////////////////////////////// */ /// @notice The desired percentage of the Vault's holdings to keep as float. /// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%. uint256 public targetFloatPercent; /// @notice Emitted when the target float percentage is updated. /// @param user The authorized user who triggered the update. /// @param newTargetFloatPercent The new target float percentage. event TargetFloatPercentUpdated(address indexed user, uint256 newTargetFloatPercent); /// @notice Set a new target float percentage. /// @param newTargetFloatPercent The new target float percentage. function setTargetFloatPercent(uint256 newTargetFloatPercent) external requiresAuth { // A target float percentage over 100% doesn't make sense. require(newTargetFloatPercent <= 1e18, "TARGET_TOO_HIGH"); // Update the target float percentage. targetFloatPercent = newTargetFloatPercent; emit TargetFloatPercentUpdated(msg.sender, newTargetFloatPercent); } /* ////////////////////////////////////////////////////////////// UNDERLYING IS WETH CONFIGURATION ///////////////////////////////////////////////////////////// */ /// @notice Whether the Vault should treat the underlying token as WETH compatible. /// @dev If enabled the Vault will allow trusting strategies that accept Ether. bool public underlyingIsWETH; /// @notice Emitted when whether the Vault should treat the underlying as WETH is updated. /// @param user The authorized user who triggered the update. /// @param newUnderlyingIsWETH Whether the Vault nows treats the underlying as WETH. event UnderlyingIsWETHUpdated(address indexed user, bool newUnderlyingIsWETH); /// @notice Sets whether the Vault treats the underlying as WETH. /// @param newUnderlyingIsWETH Whether the Vault should treat the underlying as WETH. /// @dev The underlying token must have 18 decimals, to match Ether's decimal scheme. function setUnderlyingIsWETH(bool newUnderlyingIsWETH) external requiresAuth { // Ensure the underlying token's decimals match ETH if is WETH being set to true. require(!newUnderlyingIsWETH || UNDERLYING.decimals() == 18, "WRONG_DECIMALS"); // Update whether the Vault treats the underlying as WETH. underlyingIsWETH = newUnderlyingIsWETH; emit UnderlyingIsWETHUpdated(msg.sender, newUnderlyingIsWETH); } /* ////////////////////////////////////////////////////////////// STRATEGY STORAGE ///////////////////////////////////////////////////////////// */ /// @notice The total amount of underlying tokens held in strategies at the time of the last harvest. /// @dev Includes maxLockedProfit, must be correctly subtracted to compute available/free holdings. uint256 public totalStrategyHoldings; /// @dev Packed struct of strategy data. /// @param trusted Whether the strategy is trusted. /// @param balance The amount of underlying tokens held in the strategy. struct StrategyData { // Used to determine if the Vault will operate on a strategy. bool trusted; // Used to determine profit and loss during harvests of the strategy. uint248 balance; } /// @notice Maps strategies to data the Vault holds on them. mapping(Strategy => StrategyData) public getStrategyData; /* ////////////////////////////////////////////////////////////// HARVEST STORAGE ///////////////////////////////////////////////////////////// */ /// @notice A timestamp representing when the first harvest in the most recent harvest window occurred. /// @dev May be equal to lastHarvest if there was/has only been one harvest in the most last/current window. uint64 public lastHarvestWindowStart; /// @notice A timestamp representing when the most recent harvest occurred. uint64 public lastHarvest; /// @notice The amount of locked profit at the end of the last harvest. uint128 public maxLockedProfit; /* ////////////////////////////////////////////////////////////// WITHDRAWAL STACK STORAGE ///////////////////////////////////////////////////////////// */ /// @notice An ordered array of strategies representing the withdrawal stack. /// @dev The stack is processed in descending order, meaning the last index will be withdrawn from first. /// @dev Strategies that are untrusted, duplicated, or have no balance are filtered out when encountered at /// withdrawal time, not validated upfront, meaning the stack may not reflect the "true" set used for withdrawals. Strategy[] public withdrawalStack; /// @notice Gets the full withdrawal stack. /// @return An ordered array of strategies representing the withdrawal stack. /// @dev This is provided because Solidity converts public arrays into index getters, /// but we need a way to allow external contracts and users to access the whole array. function getWithdrawalStack() external view returns (Strategy[] memory) { return withdrawalStack; } /* ////////////////////////////////////////////////////////////// DEPOSIT/WITHDRAWAL LOGIC ///////////////////////////////////////////////////////////// */ /// @notice Emitted after a successful deposit. /// @param user The address that deposited into the Vault. /// @param underlyingAmount The amount of underlying tokens that were deposited. event Deposit(address indexed user, uint256 underlyingAmount); /// @notice Emitted after a successful withdrawal. /// @param user The address that withdrew from the Vault. /// @param underlyingAmount The amount of underlying tokens that were withdrawn. event Withdraw(address indexed user, uint256 underlyingAmount); /// @notice Deposit a specific amount of underlying tokens. /// @param underlyingAmount The amount of the underlying token to deposit. function deposit(uint256 underlyingAmount) external { // Determine the equivalent amount of avTokens and mint them. _mint(msg.sender, underlyingAmount.fdiv(exchangeRate(), BASE_UNIT)); emit Deposit(msg.sender, underlyingAmount); // Transfer in underlying tokens from the user. // This will revert if the user does not have the amount specified. UNDERLYING.safeTransferFrom(msg.sender, address(this), underlyingAmount); } /// @notice Withdraw a specific amount of underlying tokens. /// @param underlyingAmount The amount of underlying tokens to withdraw. function withdraw(uint256 underlyingAmount) external { // Determine the equivalent amount of avTokens and burn them. // This will revert if the user does not have enough avTokens. _burn(msg.sender, underlyingAmount.fdiv(exchangeRate(), BASE_UNIT)); emit Withdraw(msg.sender, underlyingAmount); // Withdraw from strategies if needed and transfer. transferUnderlyingTo(msg.sender, underlyingAmount); } /// @notice Redeem a specific amount of avTokens for underlying tokens. /// @param avTokenAmount The amount of avTokens to redeem for underlying tokens. function redeem(uint256 avTokenAmount) external { // Determine the equivalent amount of underlying tokens. uint256 underlyingAmount = avTokenAmount.fmul(exchangeRate(), BASE_UNIT); // Burn the provided amount of avTokens. // This will revert if the user does not have enough avTokens. _burn(msg.sender, avTokenAmount); emit Withdraw(msg.sender, underlyingAmount); // Withdraw from strategies if needed and transfer. transferUnderlyingTo(msg.sender, underlyingAmount); } /// @dev Transfers a specific amount of underlying tokens held in strategies and/or float to a recipient. /// @dev Only withdraws from strategies if needed and maintains the target float percentage if possible. /// @param recipient The user to transfer the underlying tokens to. /// @param underlyingAmount The amount of underlying tokens to transfer. function transferUnderlyingTo(address recipient, uint256 underlyingAmount) internal { // Get the Vault's floating balance. uint256 float = totalFloat(); // If the amount is greater than the float, withdraw from strategies. if (underlyingAmount > float) { // Compute the amount needed to reach our target float percentage. uint256 floatMissingForTarget = (totalHoldings() - underlyingAmount).fmul(targetFloatPercent, 1e18); // Compute the bare minimum amount we need for this withdrawal. uint256 floatMissingForWithdrawal = underlyingAmount - float; // Pull enough to cover the withdrawal and reach our target float percentage. pullFromWithdrawalStack(floatMissingForWithdrawal + floatMissingForTarget); } // Transfer the provided amount of underlying tokens. UNDERLYING.safeTransfer(recipient, underlyingAmount); } /* ////////////////////////////////////////////////////////////// VAULT ACCOUNTING LOGIC ///////////////////////////////////////////////////////////// */ /// @notice Returns a user's Vault balance in underlying tokens. /// @param user The user to get the underlying balance of. /// @return The user's Vault balance in underlying tokens. function balanceOfUnderlying(address user) external view returns (uint256) { return balanceOf[user].fmul(exchangeRate(), BASE_UNIT); } /// @notice Returns the amount of underlying tokens an avToken can be redeemed for. /// @return The amount of underlying tokens an avToken can be redeemed for. function exchangeRate() public view returns (uint256) { // Get the total supply of avTokens. uint256 avTokenSupply = totalSupply; // If there are no avTokens in circulation, return an exchange rate of 1:1. if (avTokenSupply == 0) return BASE_UNIT; // Calculate the exchange rate by dividing the total holdings by the avToken supply. return totalHoldings().fdiv(avTokenSupply, BASE_UNIT); } /// @notice Calculates the total amount of underlying tokens the Vault holds. /// @return totalUnderlyingHeld The total amount of underlying tokens the Vault holds. function totalHoldings() public view returns (uint256 totalUnderlyingHeld) { unchecked { // Cannot underflow as locked profit can't exceed total strategy holdings. totalUnderlyingHeld = totalStrategyHoldings - lockedProfit(); } // Include our floating balance in the total. totalUnderlyingHeld += totalFloat(); } /// @notice Calculates the current amount of locked profit. /// @return The current amount of locked profit. function lockedProfit() public view returns (uint256) { // Get the last harvest and harvest delay. uint256 previousHarvest = lastHarvest; uint256 harvestInterval = harvestDelay; unchecked { // If the harvest delay has passed, there is no locked profit. // Cannot overflow on human timescales since harvestInterval is capped. if (block.timestamp >= previousHarvest + harvestInterval) return 0; // Get the maximum amount we could return. uint256 maximumLockedProfit = maxLockedProfit; // Compute how much profit remains locked based on the last harvest and harvest delay. // It's impossible for the previous harvest to be in the future, so this will never underflow. return maximumLockedProfit - (maximumLockedProfit * (block.timestamp - previousHarvest)) / harvestInterval; } } /// @notice Returns the amount of underlying tokens that idly sit in the Vault. /// @return The amount of underlying tokens that sit idly in the Vault. function totalFloat() public view returns (uint256) { return UNDERLYING.balanceOf(address(this)); } /* ////////////////////////////////////////////////////////////// HARVEST LOGIC ///////////////////////////////////////////////////////////// */ /// @notice Emitted after a successful harvest. /// @param user The authorized user who triggered the harvest. /// @param strategies The trusted strategies that were harvested. event Harvest(address indexed user, Strategy[] strategies); /// @notice Harvest a set of trusted strategies. /// @param strategies The trusted strategies to harvest. /// @dev Will always revert if called outside of an active /// harvest window or before the harvest delay has passed. function harvest(Strategy[] calldata strategies) external requiresAuth { // If this is the first harvest after the last window: if (block.timestamp >= lastHarvest + harvestDelay) { // Set the harvest window's start timestamp. // Cannot overflow 64 bits on human timescales. lastHarvestWindowStart = uint64(block.timestamp); } else { // We know this harvest is not the first in the window so we need to ensure it's within it. require(block.timestamp <= lastHarvestWindowStart + harvestWindow, "BAD_HARVEST_TIME"); } // Get the Vault's current total strategy holdings. uint256 oldTotalStrategyHoldings = totalStrategyHoldings; // Used to store the total profit accrued by the strategies. uint256 totalProfitAccrued; // Used to store the new total strategy holdings after harvesting. uint256 newTotalStrategyHoldings = oldTotalStrategyHoldings; // Will revert if any of the specified strategies are untrusted. for (uint256 i = 0; i < strategies.length; i++) { // Get the strategy at the current index. Strategy strategy = strategies[i]; // If an untrusted strategy could be harvested a malicious user could use // a fake strategy that over-reports holdings to manipulate the exchange rate. require(getStrategyData[strategy].trusted, "UNTRUSTED_STRATEGY"); // Get the strategy's previous and current balance. uint256 balanceLastHarvest = getStrategyData[strategy].balance; uint256 balanceThisHarvest = strategy.balanceOfUnderlying(address(this)); // Update the strategy's stored balance. Cast overflow is unrealistic. getStrategyData[strategy].balance = balanceThisHarvest.safeCastTo248(); // Increase/decrease newTotalStrategyHoldings based on the profit/loss registered. // We cannot wrap the subtraction in parenthesis as it would underflow if the strategy had a loss. newTotalStrategyHoldings = newTotalStrategyHoldings + balanceThisHarvest - balanceLastHarvest; unchecked { // Update the total profit accrued while counting losses as zero profit. // Cannot overflow as we already increased total holdings without reverting. totalProfitAccrued += balanceThisHarvest > balanceLastHarvest ? balanceThisHarvest - balanceLastHarvest // Profits since last harvest. : 0; // If the strategy registered a net loss we don't have any new profit. } } // Compute fees as the fee percent multiplied by the profit. uint256 feesAccrued = totalProfitAccrued.fmul(feePercent, 1e18); // If we accrued any fees, mint an equivalent amount of avTokens. // Authorized users can claim the newly minted avTokens via claimFees. _mint(address(this), feesAccrued.fdiv(exchangeRate(), BASE_UNIT)); // Update max unlocked profit based on any remaining locked profit plus new profit. maxLockedProfit = (lockedProfit() + totalProfitAccrued - feesAccrued).safeCastTo128(); // Set strategy holdings to our new total. totalStrategyHoldings = newTotalStrategyHoldings; // Update the last harvest timestamp. // Cannot overflow on human timescales. lastHarvest = uint64(block.timestamp); emit Harvest(msg.sender, strategies); // Get the next harvest delay. uint64 newHarvestDelay = nextHarvestDelay; // If the next harvest delay is not 0: if (newHarvestDelay != 0) { // Update the harvest delay. harvestDelay = newHarvestDelay; // Reset the next harvest delay. nextHarvestDelay = 0; emit HarvestDelayUpdated(msg.sender, newHarvestDelay); } } /* ////////////////////////////////////////////////////////////// STRATEGY DEPOSIT/WITHDRAWAL LOGIC ///////////////////////////////////////////////////////////// */ /// @notice Emitted after the Vault deposits into a strategy contract. /// @param user The authorized user who triggered the deposit. /// @param strategy The strategy that was deposited into. /// @param underlyingAmount The amount of underlying tokens that were deposited. event StrategyDeposit(address indexed user, Strategy indexed strategy, uint256 underlyingAmount); /// @notice Emitted after the Vault withdraws funds from a strategy contract. /// @param user The authorized user who triggered the withdrawal. /// @param strategy The strategy that was withdrawn from. /// @param underlyingAmount The amount of underlying tokens that were withdrawn. event StrategyWithdrawal(address indexed user, Strategy indexed strategy, uint256 underlyingAmount); /// @notice Deposit a specific amount of float into a trusted strategy. /// @param strategy The trusted strategy to deposit into. /// @param underlyingAmount The amount of underlying tokens in float to deposit. function depositIntoStrategy(Strategy strategy, uint256 underlyingAmount) external requiresAuth { // A strategy must be trusted before it can be deposited into. require(getStrategyData[strategy].trusted, "UNTRUSTED_STRATEGY"); // Increase totalStrategyHoldings to account for the deposit. totalStrategyHoldings += underlyingAmount; unchecked { // Without this the next harvest would count the deposit as profit. // Cannot overflow as the balance of one strategy can't exceed the sum of all. getStrategyData[strategy].balance += underlyingAmount.safeCastTo248(); } emit StrategyDeposit(msg.sender, strategy, underlyingAmount); // We need to deposit differently if the strategy takes ETH. if (strategy.isCEther()) { // Unwrap the right amount of WETH. WETH(payable(address(UNDERLYING))).withdraw(underlyingAmount); // Deposit into the strategy and assume it will revert on error. ETHStrategy(address(strategy)).mint{value: underlyingAmount}(); } else { // Approve underlyingAmount to the strategy so we can deposit. UNDERLYING.safeApprove(address(strategy), underlyingAmount); // Deposit into the strategy and revert if it returns an error code. require(ERC20Strategy(address(strategy)).mint(underlyingAmount) == 0, "MINT_FAILED"); } } /// @notice Withdraw a specific amount of underlying tokens from a strategy. /// @param strategy The strategy to withdraw from. /// @param underlyingAmount The amount of underlying tokens to withdraw. /// @dev Withdrawing from a strategy will not remove it from the withdrawal stack. function withdrawFromStrategy(Strategy strategy, uint256 underlyingAmount) external requiresAuth { // A strategy must be trusted before it can be withdrawn from. require(getStrategyData[strategy].trusted, "UNTRUSTED_STRATEGY"); // Without this the next harvest would count the withdrawal as a loss. getStrategyData[strategy].balance -= underlyingAmount.safeCastTo248(); unchecked { // Decrease totalStrategyHoldings to account for the withdrawal. // Cannot underflow as the balance of one strategy will never exceed the sum of all. totalStrategyHoldings -= underlyingAmount; } emit StrategyWithdrawal(msg.sender, strategy, underlyingAmount); // Withdraw from the strategy and revert if it returns an error code. require(strategy.redeemUnderlying(underlyingAmount) == 0, "REDEEM_FAILED"); // Wrap the withdrawn Ether into WETH if necessary. if (strategy.isCEther()) WETH(payable(address(UNDERLYING))).deposit{value: underlyingAmount}(); } /* ////////////////////////////////////////////////////////////// STRATEGY TRUST/DISTRUST LOGIC ///////////////////////////////////////////////////////////// */ /// @notice Emitted when a strategy is set to trusted. /// @param user The authorized user who trusted the strategy. /// @param strategy The strategy that became trusted. event StrategyTrusted(address indexed user, Strategy indexed strategy); /// @notice Emitted when a strategy is set to untrusted. /// @param user The authorized user who untrusted the strategy. /// @param strategy The strategy that became untrusted. event StrategyDistrusted(address indexed user, Strategy indexed strategy); /// @notice Stores a strategy as trusted, enabling it to be harvested. /// @param strategy The strategy to make trusted. function trustStrategy(Strategy strategy) external requiresAuth { // Ensure the strategy accepts the correct underlying token. // If the strategy accepts ETH the Vault should accept WETH, it'll handle wrapping when necessary. require( strategy.isCEther() ? underlyingIsWETH : ERC20Strategy(address(strategy)).underlying() == UNDERLYING, "WRONG_UNDERLYING" ); // Store the strategy as trusted. getStrategyData[strategy].trusted = true; emit StrategyTrusted(msg.sender, strategy); } /// @notice Stores a strategy as untrusted, disabling it from being harvested. /// @param strategy The strategy to make untrusted. function distrustStrategy(Strategy strategy) external requiresAuth { // Store the strategy as untrusted. getStrategyData[strategy].trusted = false; emit StrategyDistrusted(msg.sender, strategy); } /* ////////////////////////////////////////////////////////////// WITHDRAWAL STACK LOGIC ///////////////////////////////////////////////////////////// */ /// @notice Emitted when a strategy is pushed to the withdrawal stack. /// @param user The authorized user who triggered the push. /// @param pushedStrategy The strategy pushed to the withdrawal stack. event WithdrawalStackPushed(address indexed user, Strategy indexed pushedStrategy); /// @notice Emitted when a strategy is popped from the withdrawal stack. /// @param user The authorized user who triggered the pop. /// @param poppedStrategy The strategy popped from the withdrawal stack. event WithdrawalStackPopped(address indexed user, Strategy indexed poppedStrategy); /// @notice Emitted when the withdrawal stack is updated. /// @param user The authorized user who triggered the set. /// @param replacedWithdrawalStack The new withdrawal stack. event WithdrawalStackSet(address indexed user, Strategy[] replacedWithdrawalStack); /// @notice Emitted when an index in the withdrawal stack is replaced. /// @param user The authorized user who triggered the replacement. /// @param index The index of the replaced strategy in the withdrawal stack. /// @param replacedStrategy The strategy in the withdrawal stack that was replaced. /// @param replacementStrategy The strategy that overrode the replaced strategy at the index. event WithdrawalStackIndexReplaced( address indexed user, uint256 index, Strategy indexed replacedStrategy, Strategy indexed replacementStrategy ); /// @notice Emitted when an index in the withdrawal stack is replaced with the tip. /// @param user The authorized user who triggered the replacement. /// @param index The index of the replaced strategy in the withdrawal stack. /// @param replacedStrategy The strategy in the withdrawal stack replaced by the tip. /// @param previousTipStrategy The previous tip of the stack that replaced the strategy. event WithdrawalStackIndexReplacedWithTip( address indexed user, uint256 index, Strategy indexed replacedStrategy, Strategy indexed previousTipStrategy ); /// @notice Emitted when the strategies at two indexes are swapped. /// @param user The authorized user who triggered the swap. /// @param index1 One index involved in the swap /// @param index2 The other index involved in the swap. /// @param newStrategy1 The strategy (previously at index2) that replaced index1. /// @param newStrategy2 The strategy (previously at index1) that replaced index2. event WithdrawalStackIndexesSwapped( address indexed user, uint256 index1, uint256 index2, Strategy indexed newStrategy1, Strategy indexed newStrategy2 ); /// @dev Withdraw a specific amount of underlying tokens from strategies in the withdrawal stack. /// @param underlyingAmount The amount of underlying tokens to pull into float. /// @dev Automatically removes depleted strategies from the withdrawal stack. function pullFromWithdrawalStack(uint256 underlyingAmount) internal { // We will update this variable as we pull from strategies. uint256 amountLeftToPull = underlyingAmount; // We'll start at the tip of the stack and traverse backwards. uint256 currentIndex = withdrawalStack.length - 1; // Iterate in reverse so we pull from the stack in a "last in, first out" manner. // Will revert due to underflow if we empty the stack before pulling the desired amount. for (; ; currentIndex--) { // Get the strategy at the current stack index. Strategy strategy = withdrawalStack[currentIndex]; // Get the balance of the strategy before we withdraw from it. uint256 strategyBalance = getStrategyData[strategy].balance; // If the strategy is currently untrusted or was already depleted: if (!getStrategyData[strategy].trusted || strategyBalance == 0) { // Remove it from the stack. withdrawalStack.pop(); emit WithdrawalStackPopped(msg.sender, strategy); // Move onto the next strategy. continue; } // We want to pull as much as we can from the strategy, but no more than we need. uint256 amountToPull = strategyBalance > amountLeftToPull ? amountLeftToPull : strategyBalance; unchecked { // Compute the balance of the strategy that will remain after we withdraw. // Cannot underflow as we cap the amount to pull at the strategy's balance. uint256 strategyBalanceAfterWithdrawal = strategyBalance - amountToPull; // Without this the next harvest would count the withdrawal as a loss. getStrategyData[strategy].balance = strategyBalanceAfterWithdrawal.safeCastTo248(); // Adjust our goal based on how much we can pull from the strategy. // Cannot underflow as we cap the amount to pull at the amount left to pull. amountLeftToPull -= amountToPull; emit StrategyWithdrawal(msg.sender, strategy, amountToPull); // Withdraw from the strategy and revert if returns an error code. require(strategy.redeemUnderlying(amountToPull) == 0, "REDEEM_FAILED"); // If we fully depleted the strategy: if (strategyBalanceAfterWithdrawal == 0) { // Remove it from the stack. withdrawalStack.pop(); emit WithdrawalStackPopped(msg.sender, strategy); } } // If we've pulled all we need, exit the loop. if (amountLeftToPull == 0) break; } unchecked { // Account for the withdrawals done in the loop above. // Cannot underflow as the balances of some strategies cannot exceed the sum of all. totalStrategyHoldings -= underlyingAmount; } // Cache the Vault's balance of ETH. uint256 ethBalance = address(this).balance; // If the Vault's underlying token is WETH compatible and we have some ETH, wrap it into WETH. if (ethBalance != 0 && underlyingIsWETH) WETH(payable(address(UNDERLYING))).deposit{value: ethBalance}(); } /// @notice Pushes a single strategy to front of the withdrawal stack. /// @param strategy The strategy to be inserted at the front of the withdrawal stack. /// @dev Strategies that are untrusted, duplicated, or have no balance are /// filtered out when encountered at withdrawal time, not validated upfront. function pushToWithdrawalStack(Strategy strategy) external requiresAuth { // Ensure pushing the strategy will not cause the stack exceed its limit. require(withdrawalStack.length < MAX_WITHDRAWAL_STACK_SIZE, "STACK_FULL"); // Push the strategy to the front of the stack. withdrawalStack.push(strategy); emit WithdrawalStackPushed(msg.sender, strategy); } /// @notice Removes the strategy at the tip of the withdrawal stack. /// @dev Be careful, another authorized user could push a different strategy /// than expected to the stack while a popFromWithdrawalStack transaction is pending. function popFromWithdrawalStack() external requiresAuth { // Get the (soon to be) popped strategy. Strategy poppedStrategy = withdrawalStack[withdrawalStack.length - 1]; // Pop the first strategy in the stack. withdrawalStack.pop(); emit WithdrawalStackPopped(msg.sender, poppedStrategy); } /// @notice Sets a new withdrawal stack. /// @param newStack The new withdrawal stack. /// @dev Strategies that are untrusted, duplicated, or have no balance are /// filtered out when encountered at withdrawal time, not validated upfront. function setWithdrawalStack(Strategy[] calldata newStack) external requiresAuth { // Ensure the new stack is not larger than the maximum stack size. require(newStack.length <= MAX_WITHDRAWAL_STACK_SIZE, "STACK_TOO_BIG"); // Replace the withdrawal stack. withdrawalStack = newStack; emit WithdrawalStackSet(msg.sender, newStack); } /// @notice Replaces an index in the withdrawal stack with another strategy. /// @param index The index in the stack to replace. /// @param replacementStrategy The strategy to override the index with. /// @dev Strategies that are untrusted, duplicated, or have no balance are /// filtered out when encountered at withdrawal time, not validated upfront. function replaceWithdrawalStackIndex(uint256 index, Strategy replacementStrategy) external requiresAuth { // Get the (soon to be) replaced strategy. Strategy replacedStrategy = withdrawalStack[index]; // Update the index with the replacement strategy. withdrawalStack[index] = replacementStrategy; emit WithdrawalStackIndexReplaced(msg.sender, index, replacedStrategy, replacementStrategy); } /// @notice Moves the strategy at the tip of the stack to the specified index and pop the tip off the stack. /// @param index The index of the strategy in the withdrawal stack to replace with the tip. function replaceWithdrawalStackIndexWithTip(uint256 index) external requiresAuth { // Get the (soon to be) previous tip and strategy we will replace at the index. Strategy previousTipStrategy = withdrawalStack[withdrawalStack.length - 1]; Strategy replacedStrategy = withdrawalStack[index]; // Replace the index specified with the tip of the stack. withdrawalStack[index] = previousTipStrategy; // Remove the now duplicated tip from the array. withdrawalStack.pop(); emit WithdrawalStackIndexReplacedWithTip(msg.sender, index, replacedStrategy, previousTipStrategy); } /// @notice Swaps two indexes in the withdrawal stack. /// @param index1 One index involved in the swap /// @param index2 The other index involved in the swap. function swapWithdrawalStackIndexes(uint256 index1, uint256 index2) external requiresAuth { // Get the (soon to be) new strategies at each index. Strategy newStrategy2 = withdrawalStack[index1]; Strategy newStrategy1 = withdrawalStack[index2]; // Swap the strategies at both indexes. withdrawalStack[index1] = newStrategy1; withdrawalStack[index2] = newStrategy2; emit WithdrawalStackIndexesSwapped(msg.sender, index1, index2, newStrategy1, newStrategy2); } /* ////////////////////////////////////////////////////////////// SEIZE STRATEGY LOGIC ///////////////////////////////////////////////////////////// */ /// @notice Emitted after a strategy is seized. /// @param user The authorized user who triggered the seize. /// @param strategy The strategy that was seized. event StrategySeized(address indexed user, Strategy indexed strategy); /// @notice Seizes a strategy. /// @param strategy The strategy to seize. /// @dev Intended for use in emergencies or other extraneous situations where the /// strategy requires interaction outside of the Vault's standard operating procedures. function seizeStrategy(Strategy strategy) external requiresAuth { // Get the strategy's last reported balance of underlying tokens. uint256 strategyBalance = getStrategyData[strategy].balance; // If the strategy's balance exceeds the Vault's current // holdings, instantly unlock any remaining locked profit. if (strategyBalance > totalHoldings()) maxLockedProfit = 0; // Set the strategy's balance to 0. getStrategyData[strategy].balance = 0; unchecked { // Decrease totalStrategyHoldings to account for the seize. // Cannot underflow as the balance of one strategy will never exceed the sum of all. totalStrategyHoldings -= strategyBalance; } emit StrategySeized(msg.sender, strategy); // Transfer all of the strategy's tokens to the caller. ERC20(strategy).safeTransfer(msg.sender, strategy.balanceOf(address(this))); } /* ////////////////////////////////////////////////////////////// FEE CLAIM LOGIC ///////////////////////////////////////////////////////////// */ /// @notice Emitted after fees are claimed. /// @param user The authorized user who claimed the fees. /// @param avTokenAmount The amount of avTokens that were claimed. event FeesClaimed(address indexed user, uint256 avTokenAmount); /// @notice Claims fees accrued from harvests. /// @param avTokenAmount The amount of avTokens to claim. /// @dev Accrued fees are measured as avTokens held by the Vault. function claimFees(uint256 avTokenAmount) external requiresAuth { emit FeesClaimed(msg.sender, avTokenAmount); // Transfer the provided amount of avTokens to the caller. ERC20(this).safeTransfer(msg.sender, avTokenAmount); } /* ////////////////////////////////////////////////////////////// INITIALIZATION AND DESTRUCTION LOGIC ///////////////////////////////////////////////////////////// */ /// @notice Emitted when the Vault is initialized. /// @param user The authorized user who triggered the initialization. event Initialized(address indexed user); /// @notice Whether the Vault has been initialized yet. /// @dev Can go from false to true, never from true to false. bool public isInitialized; /// @notice Initializes the Vault, enabling it to receive deposits. /// @dev All critical parameters must already be set before calling. function initialize() external requiresAuth { // Ensure the Vault has not already been initialized. require(!isInitialized, "ALREADY_INITIALIZED"); // Mark the Vault as initialized. isInitialized = true; // Open for deposits. totalSupply = 0; emit Initialized(msg.sender); } /// @notice Self destructs a Vault, enabling it to be redeployed. /// @dev Caller will receive any ETH held as float in the Vault. function destroy() external requiresAuth { selfdestruct(payable(msg.sender)); } /* ////////////////////////////////////////////////////////////// RECIEVE ETHER LOGIC ///////////////////////////////////////////////////////////// */ /// @dev Required for the Vault to receive unwrapped ETH. receive() external payable {} }
Calculates the total amount of underlying tokens the Vault holds. return totalUnderlyingHeld The total amount of underlying tokens the Vault holds. Cannot underflow as locked profit can't exceed total strategy holdings.
function totalHoldings() public view returns (uint256 totalUnderlyingHeld) { unchecked { totalUnderlyingHeld = totalStrategyHoldings - lockedProfit(); } }
314,904
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../../pool-utils/contracts/oracle/PoolPriceOracle.sol"; import "../../../pool-utils/contracts/interfaces/IRateProvider.sol"; import "../../../solidity-utils/contracts/helpers/BalancerErrors.sol"; import "../../../solidity-utils/contracts/helpers/LogCompression.sol"; import "../../../solidity-utils/contracts/math/FixedPoint.sol"; import "../StablePool.sol"; import "./OracleMiscData.sol"; import "./StableOracleMath.sol"; /** * @dev StablePool suitable for assets with proportional prices (i.e. with slow-changing exchange rates between them). * Requires an external feed of these exchange rates. * * It additionally features a price oracle. */ contract MetaStablePool is StablePool, StableOracleMath, PoolPriceOracle { using WordCodec for bytes32; using FixedPoint for uint256; using OracleMiscData for bytes32; IRateProvider private immutable _rateProvider0; IRateProvider private immutable _rateProvider1; // Price rate caches are used to avoid querying the price rate for a token every time we need to work with it. // Data is stored with the following structure: // // [ expires | duration | price rate value ] // [ uint64 | uint64 | uint128 ] bytes32 private _priceRateCache0; bytes32 private _priceRateCache1; uint256 private constant _PRICE_RATE_CACHE_VALUE_OFFSET = 0; uint256 private constant _PRICE_RATE_CACHE_DURATION_OFFSET = 128; uint256 private constant _PRICE_RATE_CACHE_EXPIRES_OFFSET = 128 + 64; event OracleEnabledChanged(bool enabled); event PriceRateProviderSet(IERC20 indexed token, IRateProvider indexed provider, uint256 cacheDuration); event PriceRateCacheUpdated(IERC20 indexed token, uint256 rate); // The constructor arguments are received in a struct to work around stack-too-deep issues struct NewPoolParams { IVault vault; string name; string symbol; IERC20[] tokens; IRateProvider[] rateProviders; uint256[] priceRateCacheDuration; uint256 amplificationParameter; uint256 swapFeePercentage; uint256 pauseWindowDuration; uint256 bufferPeriodDuration; bool oracleEnabled; address owner; } constructor(NewPoolParams memory params) StablePool( params.vault, params.name, params.symbol, params.tokens, params.amplificationParameter, params.swapFeePercentage, params.pauseWindowDuration, params.bufferPeriodDuration, params.owner ) { _require(params.tokens.length == 2, Errors.NOT_TWO_TOKENS); InputHelpers.ensureInputLengthMatch( params.tokens.length, params.rateProviders.length, params.priceRateCacheDuration.length ); // Set providers and initialise cache. We can't use `_setToken0PriceRateCache` as it relies on immutable // variables, which cannot be read from during construction. IRateProvider rateProvider0 = params.rateProviders[0]; _rateProvider0 = rateProvider0; if (rateProvider0 != IRateProvider(address(0))) { (bytes32 cache, uint256 rate) = _getNewPriceRateCache(rateProvider0, params.priceRateCacheDuration[0]); _priceRateCache0 = cache; emit PriceRateCacheUpdated(params.tokens[0], rate); } emit PriceRateProviderSet(params.tokens[0], rateProvider0, params.priceRateCacheDuration[0]); IRateProvider rateProvider1 = params.rateProviders[1]; _rateProvider1 = rateProvider1; if (rateProvider1 != IRateProvider(address(0))) { (bytes32 cache, uint256 rate) = _getNewPriceRateCache(rateProvider1, params.priceRateCacheDuration[1]); _priceRateCache1 = cache; emit PriceRateCacheUpdated(params.tokens[1], rate); } emit PriceRateProviderSet(params.tokens[1], rateProvider1, params.priceRateCacheDuration[1]); _setOracleEnabled(params.oracleEnabled); } // Swap function onSwap( SwapRequest memory request, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) public virtual override returns (uint256) { _cachePriceRatesIfNecessary(); return super.onSwap(request, balances, indexIn, indexOut); } function onSwap( SwapRequest memory request, uint256 balanceTokenIn, uint256 balanceTokenOut ) public virtual override returns (uint256) { _cachePriceRatesIfNecessary(); return super.onSwap(request, balanceTokenIn, balanceTokenOut); } /** * Update price oracle with the pre-swap balances */ function _onSwapGivenIn( SwapRequest memory request, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) internal virtual override returns (uint256) { _updateOracle(request.lastChangeBlock, balances[0], balances[1]); return super._onSwapGivenIn(request, balances, indexIn, indexOut); } /** * Update price oracle with the pre-swap balances */ function _onSwapGivenOut( SwapRequest memory request, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) internal virtual override returns (uint256) { _updateOracle(request.lastChangeBlock, balances[0], balances[1]); return super._onSwapGivenOut(request, balances, indexIn, indexOut); } // Join /** * @dev Update cached total supply and invariant using the results after the join that will be used for * future oracle updates. * Note that this function relies on the base class to perform any safety checks on joins. */ function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) public virtual override returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) { _cachePriceRatesIfNecessary(); (amountsIn, dueProtocolFeeAmounts) = super.onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _cacheInvariantAndSupply(); } /** * @dev Update price oracle with the pre-join balances */ function _onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual override returns ( uint256, uint256[] memory, uint256[] memory ) { _updateOracle(lastChangeBlock, balances[0], balances[1]); return super._onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); } // Exit /** * @dev Update cached total supply and invariant using the results after the exit that will be used for * future oracle updates. * Note that this function relies on the base class to perform any safety checks on exits. */ function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) public virtual override returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) { _cachePriceRatesIfNecessary(); (amountsOut, dueProtocolFeeAmounts) = super.onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // If the contract is paused, the oracle is not updated to avoid extra calculations and reduce potential errors. if (_isNotPaused()) { _cacheInvariantAndSupply(); } } /** * @dev Update price oracle with the pre-exit balances */ function _onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // If the contract is paused, the oracle is not updated to avoid extra calculations and reduce potential errors. if (_isNotPaused()) { _updateOracle(lastChangeBlock, balances[0], balances[1]); } return super._onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); } // Oracle function getOracleMiscData() external view returns ( int256 logInvariant, int256 logTotalSupply, uint256 oracleSampleCreationTimestamp, uint256 oracleIndex, bool oracleEnabled ) { bytes32 miscData = _getMiscData(); logInvariant = miscData.logInvariant(); logTotalSupply = miscData.logTotalSupply(); oracleSampleCreationTimestamp = miscData.oracleSampleCreationTimestamp(); oracleIndex = miscData.oracleIndex(); oracleEnabled = miscData.oracleEnabled(); } /** * @dev Balancer Governance can always enable the Oracle, even if it was originally not enabled. This allows for * Pools that unexpectedly drive much more volume and liquidity than expected to serve as Price Oracles. * * Note that the Oracle can only be enabled - it can never be disabled. */ function enableOracle() external whenNotPaused authenticate { _setOracleEnabled(true); // Cache log invariant and supply only if the pool was initialized if (totalSupply() > 0) { _cacheInvariantAndSupply(); } } function _setOracleEnabled(bool enabled) internal { _setMiscData(_getMiscData().setOracleEnabled(enabled)); emit OracleEnabledChanged(enabled); } /** * @dev Updates the Price Oracle based on the Pool's current state (balances, BPT supply and invariant). Must be * called on *all* state-changing functions with the balances *before* the state change happens, and with * `lastChangeBlock` as the number of the block in which any of the balances last changed. */ function _updateOracle( uint256 lastChangeBlock, uint256 balance0, uint256 balance1 ) internal { bytes32 miscData = _getMiscData(); (uint256 currentAmp, ) = _getAmplificationParameter(); if (miscData.oracleEnabled() && block.number > lastChangeBlock) { (int256 logSpotPrice, int256 logBptPrice) = StableOracleMath._calcLogPrices( currentAmp, balance0, balance1, miscData.logTotalSupply() ); uint256 oracleCurrentIndex = miscData.oracleIndex(); uint256 oracleCurrentSampleInitialTimestamp = miscData.oracleSampleCreationTimestamp(); uint256 oracleUpdatedIndex = _processPriceData( oracleCurrentSampleInitialTimestamp, oracleCurrentIndex, logSpotPrice, logBptPrice, miscData.logInvariant() ); if (oracleCurrentIndex != oracleUpdatedIndex) { // solhint-disable not-rely-on-time miscData = miscData.setOracleIndex(oracleUpdatedIndex); miscData = miscData.setOracleSampleCreationTimestamp(block.timestamp); _setMiscData(miscData); } } } /** * @dev Stores the logarithm of the invariant and BPT total supply, to be later used in each oracle update. Because * it is stored in miscData, which is read in all operations (including swaps), this saves gas by not requiring to * compute or read these values when updating the oracle. * * This function must be called by all actions that update the invariant and BPT supply (joins and exits). Swaps * also alter the invariant due to collected swap fees, but this growth is considered negligible and not accounted * for. */ function _cacheInvariantAndSupply() internal { bytes32 miscData = _getMiscData(); if (miscData.oracleEnabled()) { miscData = miscData.setLogInvariant(LogCompression.toLowResLog(_lastInvariant)); miscData = miscData.setLogTotalSupply(LogCompression.toLowResLog(totalSupply())); _setMiscData(miscData); } } function _getOracleIndex() internal view override returns (uint256) { return _getMiscData().oracleIndex(); } // Scaling factors /** * @dev Overrides scaling factor getter to introduce the token's price rate * Note that it may update the price rate cache if necessary. */ function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) { uint256 baseScalingFactor = super._scalingFactor(token); uint256 priceRate = _priceRate(token); // Given there is no generic direction for this rounding, it simply follows the same strategy as the BasePool. return baseScalingFactor.mulDown(priceRate); } /** * @dev Overrides scaling factor getter to introduce the tokens' price rate. * Note that it may update the price rate cache if necessary. */ function _scalingFactors() internal view virtual override returns (uint256[] memory scalingFactors) { // There is no need to check the arrays length since both are based on `_getTotalTokens` // Given there is no generic direction for this rounding, it simply follows the same strategy as the BasePool. scalingFactors = super._scalingFactors(); scalingFactors[0] = scalingFactors[0].mulDown(_priceRate(_token0)); scalingFactors[1] = scalingFactors[1].mulDown(_priceRate(_token1)); } // Price rates /** * @dev Returns the rate providers configured for each token (in the same order as registered). */ function getRateProviders() external view returns (IRateProvider[] memory providers) { providers = new IRateProvider[](2); providers[0] = _getRateProvider0(); providers[1] = _getRateProvider1(); } /** * @dev Returns the cached value for token's rate */ function getPriceRateCache(IERC20 token) external view returns ( uint256 rate, uint256 duration, uint256 expires ) { if (_isToken0(token)) return _getPriceRateCache(_getPriceRateCache0()); if (_isToken1(token)) return _getPriceRateCache(_getPriceRateCache1()); _revert(Errors.INVALID_TOKEN); } /** * @dev Sets a new duration for a token price rate cache. It reverts if there was no rate provider set initially. * Note this function also updates the current cached value. * @param duration Number of seconds until the current rate of token price is fetched again. */ function setPriceRateCacheDuration(IERC20 token, uint256 duration) external authenticate { if (_isToken0WithRateProvider(token)) { _updateToken0PriceRateCache(duration); emit PriceRateProviderSet(token, _getRateProvider0(), duration); } else if (_isToken1WithRateProvider(token)) { _updateToken1PriceRateCache(duration); emit PriceRateProviderSet(token, _getRateProvider1(), duration); } else { _revert(Errors.INVALID_TOKEN); } } function updatePriceRateCache(IERC20 token) external { if (_isToken0WithRateProvider(token)) { _updateToken0PriceRateCache(); } else if (_isToken1WithRateProvider(token)) { _updateToken1PriceRateCache(); } else { _revert(Errors.INVALID_TOKEN); } } /** * @dev Returns the price rate for token. All price rates are fixed-point values with 18 decimals. * In case there is no rate provider for the provided token it returns 1e18. */ function _priceRate(IERC20 token) internal view virtual returns (uint256) { // Given that this function is only used by `onSwap` which can only be called by the vault in the case of a // Meta Stable Pool, we can be sure the vault will not forward a call with an invalid `token` param. if (_isToken0WithRateProvider(token)) { return _getPriceRateCacheValue(_getPriceRateCache0()); } else if (_isToken1WithRateProvider(token)) { return _getPriceRateCacheValue(_getPriceRateCache1()); } else { return FixedPoint.ONE; } } function _cachePriceRatesIfNecessary() internal { _cachePriceRate0IfNecessary(); _cachePriceRate1IfNecessary(); } function _cachePriceRate0IfNecessary() private { if (_getRateProvider0() != IRateProvider(address(0))) { (uint256 duration, uint256 expires) = _getPriceRateCacheTimestamps(_getPriceRateCache0()); if (block.timestamp > expires) { _updateToken0PriceRateCache(duration); } } } function _cachePriceRate1IfNecessary() private { if (_getRateProvider1() != IRateProvider(address(0))) { (uint256 duration, uint256 expires) = _getPriceRateCacheTimestamps(_getPriceRateCache1()); if (block.timestamp > expires) { _updateToken1PriceRateCache(duration); } } } /** * @dev Decodes a price rate cache into rate value, duration and expiration time */ function _getPriceRateCache(bytes32 cache) private pure returns ( uint256 rate, uint256 duration, uint256 expires ) { rate = _getPriceRateCacheValue(cache); (duration, expires) = _getPriceRateCacheTimestamps(cache); } /** * @dev Decodes the rate value for a price rate cache */ function _getPriceRateCacheValue(bytes32 cache) private pure returns (uint256) { return cache.decodeUint128(_PRICE_RATE_CACHE_VALUE_OFFSET); } /** * @dev Decodes the duration for a price rate cache */ function _getPriceRateCacheDuration(bytes32 cache) private pure returns (uint256) { return cache.decodeUint64(_PRICE_RATE_CACHE_DURATION_OFFSET); } /** * @dev Decodes the duration and expiration timestamp for a price rate cache */ function _getPriceRateCacheTimestamps(bytes32 cache) private pure returns (uint256 duration, uint256 expires) { duration = _getPriceRateCacheDuration(cache); expires = cache.decodeUint64(_PRICE_RATE_CACHE_EXPIRES_OFFSET); } function _updateToken0PriceRateCache() private { _updateToken0PriceRateCache(_getPriceRateCacheDuration(_getPriceRateCache0())); } function _updateToken0PriceRateCache(uint256 duration) private { (bytes32 cache, uint256 rate) = _getNewPriceRateCache(_getRateProvider0(), duration); _setToken0PriceRateCache(cache, rate); } function _updateToken1PriceRateCache() private { _updateToken1PriceRateCache(_getPriceRateCacheDuration(_getPriceRateCache1())); } function _updateToken1PriceRateCache(uint256 duration) private { (bytes32 cache, uint256 rate) = _getNewPriceRateCache(_getRateProvider1(), duration); _setToken1PriceRateCache(cache, rate); } function _setToken0PriceRateCache(bytes32 cache, uint256 rate) private { _priceRateCache0 = cache; emit PriceRateCacheUpdated(_token0, rate); } function _setToken1PriceRateCache(bytes32 cache, uint256 rate) private { _priceRateCache1 = cache; emit PriceRateCacheUpdated(_token1, rate); } /** * @dev Fetches the current price rate from a provider and builds a new price rate cache */ function _getNewPriceRateCache(IRateProvider provider, uint256 duration) private view returns (bytes32 cache, uint256 rate) { rate = provider.getRate(); _require(rate < 2**128, Errors.PRICE_RATE_OVERFLOW); cache = WordCodec.encodeUint(uint128(rate), _PRICE_RATE_CACHE_VALUE_OFFSET) | WordCodec.encodeUint(uint64(duration), _PRICE_RATE_CACHE_DURATION_OFFSET) | WordCodec.encodeUint(uint64(block.timestamp + duration), _PRICE_RATE_CACHE_EXPIRES_OFFSET); } function _isToken0WithRateProvider(IERC20 token) internal view returns (bool) { return _isToken0(token) && _getRateProvider0() != IRateProvider(address(0)); } function _isToken1WithRateProvider(IERC20 token) internal view returns (bool) { return _isToken1(token) && _getRateProvider1() != IRateProvider(address(0)); } function _getRateProvider0() internal view returns (IRateProvider) { return _rateProvider0; } function _getRateProvider1() internal view returns (IRateProvider) { return _rateProvider1; } function _getPriceRateCache0() internal view returns (bytes32) { return _priceRateCache0; } function _getPriceRateCache1() internal view returns (bytes32) { return _priceRateCache1; } }
Update cached total supply and invariant using the results after the join that will be used for future oracle updates. Note that this function relies on the base class to perform any safety checks on joins./
function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) public virtual override returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) { _cachePriceRatesIfNecessary(); (amountsIn, dueProtocolFeeAmounts) = super.onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _cacheInvariantAndSupply(); }
928,954
./full_match/42220/0x5bd084845f8Ce18384d361BF8F4742EAd18eeD3d/sources/contracts/DefaultStrategy.sol
Distributes votes by computing the number of votes each active group should receive. celoAmount The amount of votes to distribute. depositGroupToIgnore The group that will not be used for deposit. return finalGroups The groups that were chosen for distribution. return finalVotes The votes of chosen finalGroups./
function generateDepositVoteDistribution(uint256 celoAmount, address depositGroupToIgnore) external managerOrStrategy returns (address[] memory finalGroups, uint256[] memory finalVotes) { return _generateDepositVoteDistribution(celoAmount, depositGroupToIgnore); }
16,332,567
./full_match/62320/0xbe9ff483BF4bEE31661340b26b0fD2e021C7CEd0/sources/lib/mento-core/contracts/BreakerBox.sol
Sets the trading mode for the specified rateFeedID. rateFeedID The address of the rateFeedID. tradingMode The trading mode that should be set./
function setRateFeedTradingMode(address rateFeedID, uint64 tradingMode) public onlyOwner { require( tradingMode == 0 || tradingModeBreaker[tradingMode] != address(0), "Trading mode must be default or have a breaker set" ); TradingModeInfo memory info = rateFeedTradingModes[rateFeedID]; require(info.lastUpdatedTime > 0, "Rate feed ID has not been added"); info.tradingMode = tradingMode; info.lastUpdatedTime = uint64(block.timestamp); info.lastUpdatedBlock = uint128(block.number); rateFeedTradingModes[rateFeedID] = info; emit TradingModeUpdated(rateFeedID, tradingMode); }
3,225,090
./partial_match/1/0xa94310AeeD50687f7c39ACdAA5FCd311AEDB25f8/sources/contracts/erc721/ERC721EditionsDFS.sol
Conforms to ERC-2981. _tokenId Token id _salePrice Sale price of token/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address receiver, uint256 royaltyAmount) { return ERC721Base.royaltyInfo(_getEditionId(_tokenId), _salePrice); }
3,645,419
./full_match/137/0x7e6Ec23e6858743b575734F0F013BeABEfff2615/sources/contracts/CaesiumBondStakeDepository.sol
determine maximum bond size return uint/
function maxPayout() public view returns (uint256) { return IERC20(CAES).totalSupply().mul(terms.maxPayout).div(100000); }
4,719,165
./full_match/1/0xFDdbc45f4cE5893962d2DEAAa03acfC6813d9C21/sources/src/FishfoodFunder.sol
Don't allow the last admin to be removed if there are funds in the contract.
function removeAdmin(address newAdmin) external { if ( !fishFoodFundingStatus[msg.sender].isAdmin || (adminCount == 1 && address(this).balance > 0) ) { revert TooBad(); } fishFoodFundingStatus[newAdmin].isAdmin = false; --adminCount; }
17,156,385
pragma solidity 0.5.15; contract IAugur { function CREATECHILDUNIVERSE712(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING function ISKNOWNUNIVERSE698(IUniverse _universe) public view returns (bool); //inject NONSTANDARD NAMING function TRUSTEDCASHTRANSFER967(address _from, address _to, uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function ISTRUSTEDSENDER635(address _address) public returns (bool); //inject NONSTANDARD NAMING function ONCATEGORICALMARKETCREATED679(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool); //inject NONSTANDARD NAMING function ONYESNOMARKETCREATED215(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool); //inject NONSTANDARD NAMING function ONSCALARMARKETCREATED844(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTSUBMITTED874(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool); //inject NONSTANDARD NAMING function DISPUTECROWDSOURCERCREATED646(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERCONTRIBUTION255(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERCOMPLETED546(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTERREDEEMED338(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERREDEEMED9(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETFINALIZED368(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETMIGRATED444(IMarket _market, IUniverse _originalUniverse) public returns (bool); //inject NONSTANDARD NAMING function LOGREPORTINGPARTICIPANTDISAVOWED43(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETPARTICIPANTSDISAVOWED537(IUniverse _universe) public returns (bool); //inject NONSTANDARD NAMING function LOGCOMPLETESETSPURCHASED486(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); //inject NONSTANDARD NAMING function LOGCOMPLETESETSSOLD144(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETOICHANGED928(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function LOGTRADINGPROCEEDSCLAIMED757(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING function LOGUNIVERSEFORKED116(IMarket _forkingMarket) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSTRANSFERRED904(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSBURNED995(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSMINTED985(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGSHARETOKENSBALANCECHANGED123(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSTRANSFERRED932(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSBURNED518(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSMINTED48(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTEWINDOWCREATED79(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSREDEEMED534(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool); //inject NONSTANDARD NAMING function LOGTIMESTAMPSET762(uint256 _newTimestamp) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTERTRANSFERRED573(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETTRANSFERRED247(IUniverse _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSTRANSFERRED386(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSBURNED957(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSMINTED248(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETREPBONDTRANSFERRED31(address _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGWARPSYNCDATAUPDATED845(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool); //inject NONSTANDARD NAMING function ISKNOWNFEESENDER211(address _feeSender) public view returns (bool); //inject NONSTANDARD NAMING function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING function GETTIMESTAMP626() public view returns (uint256); //inject NONSTANDARD NAMING function GETMAXIMUMMARKETENDDATE626() public returns (uint256); //inject NONSTANDARD NAMING function ISKNOWNMARKET166(IMarket _market) public view returns (bool); //inject NONSTANDARD NAMING function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32); //inject NONSTANDARD NAMING function LOGVALIDITYBONDCHANGED992(uint256 _validityBond) public returns (bool); //inject NONSTANDARD NAMING function LOGDESIGNATEDREPORTSTAKECHANGED748(uint256 _designatedReportStake) public returns (bool); //inject NONSTANDARD NAMING function LOGNOSHOWBONDCHANGED254(uint256 _noShowBond) public returns (bool); //inject NONSTANDARD NAMING function LOGREPORTINGFEECHANGED596(uint256 _reportingFee) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSEFORKINDEX548(IUniverse _universe) public view returns (uint256); //inject NONSTANDARD NAMING } contract IOwnable { function GETOWNER826() public view returns (address); //inject NONSTANDARD NAMING function TRANSFEROWNERSHIP284(address _newOwner) public returns (bool); //inject NONSTANDARD NAMING } contract ITyped { function GETTYPENAME153() public view returns (bytes32); //inject NONSTANDARD NAMING } library SafeMathUint256 { function MUL760(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV647(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB692(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); return a - b; } function ADD571(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MIN885(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a <= b) { return a; } else { return b; } } function MAX990(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a >= b) { return a; } else { return b; } } function SQRT858(uint256 y) internal pure returns (uint256 z) { //inject NONSTANDARD NAMING if (y > 3) { uint256 x = (y + 1) / 2; z = y; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function GETUINT256MIN331() internal pure returns (uint256) { //inject NONSTANDARD NAMING return 0; } function GETUINT256MAX467() internal pure returns (uint256) { //inject NONSTANDARD NAMING // 2 ** 256 - 1 return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; } function ISMULTIPLEOF540(uint256 a, uint256 b) internal pure returns (bool) { //inject NONSTANDARD NAMING return a % b == 0; } // Float [fixed point] Operations function FXPMUL102(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV647(MUL760(a, b), base); } function FXPDIV922(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV647(MUL760(a, base), b); } } interface IERC1155 { event TRANSFERSINGLE49( //inject NONSTANDARD NAMING address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TRANSFERBATCH882( //inject NONSTANDARD NAMING address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event APPROVALFORALL731( //inject NONSTANDARD NAMING address indexed owner, address indexed operator, bool approved ); event URI998( //inject NONSTANDARD NAMING string value, uint256 indexed id ); function SAFETRANSFERFROM689( //inject NONSTANDARD NAMING address from, address to, uint256 id, uint256 value, bytes calldata data ) external; function SAFEBATCHTRANSFERFROM779( //inject NONSTANDARD NAMING address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; function SETAPPROVALFORALL494(address operator, bool approved) external; //inject NONSTANDARD NAMING function ISAPPROVEDFORALL901(address owner, address operator) external view returns (bool); //inject NONSTANDARD NAMING function BALANCEOF492(address owner, uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY304(uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFBATCH918( //inject NONSTANDARD NAMING address[] calldata owners, uint256[] calldata ids ) external view returns (uint256[] memory balances_); } contract IERC20 { function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF492(address owner) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER644(address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM669(address from, address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function APPROVE293(address spender, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE377(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING // solhint-disable-next-line no-simple-event-func-name event TRANSFER723(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL665(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract ICash is IERC20 { } contract ERC20 is IERC20 { using SafeMathUint256 for uint256; uint8 constant public decimals866 = 18; //inject NONSTANDARD NAMING uint256 public totalSupply; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowances; function BALANCEOF492(address _account) public view returns (uint256) { //inject NONSTANDARD NAMING return balances[_account]; } function TRANSFER644(address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER433(msg.sender, _recipient, _amount); return true; } function ALLOWANCE377(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING return allowances[_owner][_spender]; } function APPROVE293(address _spender, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, _amount); return true; } function TRANSFERFROM669(address _sender, address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER433(_sender, _recipient, _amount); _APPROVE571(_sender, msg.sender, allowances[_sender][msg.sender].SUB692(_amount)); return true; } function INCREASEALLOWANCE307(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].ADD571(_addedValue)); return true; } function DECREASEALLOWANCE757(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].SUB692(_subtractedValue)); return true; } function _TRANSFER433(address _sender, address _recipient, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_sender != address(0), "ERC20: transfer from the zero address"); require(_recipient != address(0), "ERC20: transfer to the zero address"); balances[_sender] = balances[_sender].SUB692(_amount); balances[_recipient] = balances[_recipient].ADD571(_amount); emit TRANSFER723(_sender, _recipient, _amount); ONTOKENTRANSFER292(_sender, _recipient, _amount); } function _MINT880(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0), "ERC20: mint to the zero address"); totalSupply = totalSupply.ADD571(_amount); balances[_account] = balances[_account].ADD571(_amount); emit TRANSFER723(address(0), _account, _amount); } function _BURN356(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0), "ERC20: burn from the zero address"); balances[_account] = balances[_account].SUB692(_amount); totalSupply = totalSupply.SUB692(_amount); emit TRANSFER723(_account, address(0), _amount); } function _APPROVE571(address _owner, address _spender, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_owner != address(0), "ERC20: approve from the zero address"); require(_spender != address(0), "ERC20: approve to the zero address"); allowances[_owner][_spender] = _amount; emit APPROVAL665(_owner, _spender, _amount); } function _BURNFROM317(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING _BURN356(_account, _amount); _APPROVE571(_account, msg.sender, allowances[_account][msg.sender].SUB692(_amount)); } // Subclasses of this token generally want to send additional logs through the centralized Augur log emitter contract function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal; //inject NONSTANDARD NAMING } contract VariableSupplyToken is ERC20 { using SafeMathUint256 for uint256; function MINT146(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING _MINT880(_target, _amount); ONMINT315(_target, _amount); return true; } function BURN234(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING _BURN356(_target, _amount); ONBURN653(_target, _amount); return true; } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function ONMINT315(address, uint256) internal { //inject NONSTANDARD NAMING } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function ONBURN653(address, uint256) internal { //inject NONSTANDARD NAMING } } contract IAffiliateValidator { function VALIDATEREFERENCE609(address _account, address _referrer) external view returns (bool); //inject NONSTANDARD NAMING } contract IDisputeWindow is ITyped, IERC20 { function INVALIDMARKETSTOTAL511() external view returns (uint256); //inject NONSTANDARD NAMING function VALIDITYBONDTOTAL28() external view returns (uint256); //inject NONSTANDARD NAMING function INCORRECTDESIGNATEDREPORTTOTAL522() external view returns (uint256); //inject NONSTANDARD NAMING function INITIALREPORTBONDTOTAL695() external view returns (uint256); //inject NONSTANDARD NAMING function DESIGNATEDREPORTNOSHOWSTOTAL443() external view returns (uint256); //inject NONSTANDARD NAMING function DESIGNATEDREPORTERNOSHOWBONDTOTAL703() external view returns (uint256); //inject NONSTANDARD NAMING function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public; //inject NONSTANDARD NAMING function TRUSTEDBUY954(address _buyer, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IReputationToken); //inject NONSTANDARD NAMING function GETSTARTTIME383() public view returns (uint256); //inject NONSTANDARD NAMING function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING function GETWINDOWID901() public view returns (uint256); //inject NONSTANDARD NAMING function ISACTIVE720() public view returns (bool); //inject NONSTANDARD NAMING function ISOVER108() public view returns (bool); //inject NONSTANDARD NAMING function ONMARKETFINALIZED596() public; //inject NONSTANDARD NAMING function REDEEM559(address _account) public returns (bool); //inject NONSTANDARD NAMING } contract IMarket is IOwnable { enum MarketType { YES_NO, CATEGORICAL, SCALAR } function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators) public view returns (bytes32); //inject NONSTANDARD NAMING function DOINITIALREPORT448(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETDISPUTEWINDOW804() public view returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETNUMBEROFOUTCOMES636() public view returns (uint256); //inject NONSTANDARD NAMING function GETNUMTICKS752() public view returns (uint256); //inject NONSTANDARD NAMING function GETMARKETCREATORSETTLEMENTFEEDIVISOR51() public view returns (uint256); //inject NONSTANDARD NAMING function GETFORKINGMARKET637() public view returns (IMarket _market); //inject NONSTANDARD NAMING function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGPAYOUTDISTRIBUTIONHASH916() public view returns (bytes32); //inject NONSTANDARD NAMING function GETWINNINGPAYOUTNUMERATOR375(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGREPORTINGPARTICIPANT424() public view returns (IReportingParticipant); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING function GETFINALIZATIONTIME347() public view returns (uint256); //inject NONSTANDARD NAMING function GETINITIALREPORTER212() public view returns (IInitialReporter); //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTINGENDTIME834() public view returns (uint256); //inject NONSTANDARD NAMING function GETVALIDITYBONDATTOCASH123() public view returns (uint256); //inject NONSTANDARD NAMING function AFFILIATEFEEDIVISOR322() external view returns (uint256); //inject NONSTANDARD NAMING function GETNUMPARTICIPANTS137() public view returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTEPACINGON415() public view returns (bool); //inject NONSTANDARD NAMING function DERIVEMARKETCREATORFEEAMOUNT558(uint256 _amount) public view returns (uint256); //inject NONSTANDARD NAMING function RECORDMARKETCREATORFEES738(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING function ISFINALIZEDASINVALID362() public view returns (bool); //inject NONSTANDARD NAMING function FINALIZE310() public returns (bool); //inject NONSTANDARD NAMING function ISFINALIZED623() public view returns (bool); //inject NONSTANDARD NAMING function GETOPENINTEREST251() public view returns (uint256); //inject NONSTANDARD NAMING } contract IReportingParticipant { function GETSTAKE932() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTDISTRIBUTIONHASH1000() public view returns (bytes32); //inject NONSTANDARD NAMING function LIQUIDATELOSING232() public; //inject NONSTANDARD NAMING function REDEEM559(address _redeemer) public returns (bool); //inject NONSTANDARD NAMING function ISDISAVOWED173() public view returns (bool); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING function GETMARKET927() public view returns (IMarket); //inject NONSTANDARD NAMING function GETSIZE85() public view returns (uint256); //inject NONSTANDARD NAMING } contract IDisputeCrowdsourcer is IReportingParticipant, IERC20 { function INITIALIZE90(IAugur _augur, IMarket market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _crowdsourcerGeneration) public; //inject NONSTANDARD NAMING function CONTRIBUTE720(address _participant, uint256 _amount, bool _overload) public returns (uint256); //inject NONSTANDARD NAMING function SETSIZE177(uint256 _size) public; //inject NONSTANDARD NAMING function GETREMAININGTOFILL115() public view returns (uint256); //inject NONSTANDARD NAMING function CORRECTSIZE807() public returns (bool); //inject NONSTANDARD NAMING function GETCROWDSOURCERGENERATION652() public view returns (uint256); //inject NONSTANDARD NAMING } contract IInitialReporter is IReportingParticipant, IOwnable { function INITIALIZE90(IAugur _augur, IMarket _market, address _designatedReporter) public; //inject NONSTANDARD NAMING function REPORT291(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public; //inject NONSTANDARD NAMING function DESIGNATEDREPORTERSHOWED809() public view returns (bool); //inject NONSTANDARD NAMING function INITIALREPORTERWASCORRECT338() public view returns (bool); //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTER404() public view returns (address); //inject NONSTANDARD NAMING function GETREPORTTIMESTAMP304() public view returns (uint256); //inject NONSTANDARD NAMING function MIGRATETONEWUNIVERSE701(address _designatedReporter) public; //inject NONSTANDARD NAMING function RETURNREPFROMDISAVOW512() public; //inject NONSTANDARD NAMING } contract IReputationToken is IERC20 { function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETTOTALMIGRATED220() public view returns (uint256); //inject NONSTANDARD NAMING function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256); //inject NONSTANDARD NAMING function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool); //inject NONSTANDARD NAMING } contract IShareToken is ITyped, IERC1155 { function INITIALIZE90(IAugur _augur) external; //inject NONSTANDARD NAMING function INITIALIZEMARKET720(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING function UNSAFETRANSFERFROM654(address _from, address _to, uint256 _id, uint256 _value) public; //inject NONSTANDARD NAMING function UNSAFEBATCHTRANSFERFROM211(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public; //inject NONSTANDARD NAMING function CLAIMTRADINGPROCEEDS854(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees); //inject NONSTANDARD NAMING function GETMARKET927(uint256 _tokenId) external view returns (IMarket); //inject NONSTANDARD NAMING function GETOUTCOME167(uint256 _tokenId) external view returns (uint256); //inject NONSTANDARD NAMING function GETTOKENID371(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId); //inject NONSTANDARD NAMING function GETTOKENIDS530(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds); //inject NONSTANDARD NAMING function BUYCOMPLETESETS983(IMarket _market, address _account, uint256 _amount) external returns (bool); //inject NONSTANDARD NAMING function BUYCOMPLETESETSFORTRADE277(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool); //inject NONSTANDARD NAMING function SELLCOMPLETESETS485(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING function SELLCOMPLETESETSFORTRADE561(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING function TOTALSUPPLYFORMARKETOUTCOME526(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFMARKETOUTCOME21(IMarket _market, uint256 _outcome, address _account) public view returns (uint256); //inject NONSTANDARD NAMING function LOWESTBALANCEOFMARKETOUTCOMES298(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256); //inject NONSTANDARD NAMING } contract IUniverse { function CREATIONTIME597() external view returns (uint256); //inject NONSTANDARD NAMING function MARKETBALANCE692(address) external view returns (uint256); //inject NONSTANDARD NAMING function FORK341() public returns (bool); //inject NONSTANDARD NAMING function UPDATEFORKVALUES73() public returns (bool); //inject NONSTANDARD NAMING function GETPARENTUNIVERSE169() public view returns (IUniverse); //inject NONSTANDARD NAMING function CREATECHILDUNIVERSE712(uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING function GETCHILDUNIVERSE576(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING function GETFORKINGMARKET637() public view returns (IMarket); //inject NONSTANDARD NAMING function GETFORKENDTIME510() public view returns (uint256); //inject NONSTANDARD NAMING function GETFORKREPUTATIONGOAL776() public view returns (uint256); //inject NONSTANDARD NAMING function GETPARENTPAYOUTDISTRIBUTIONHASH230() public view returns (bytes32); //inject NONSTANDARD NAMING function GETDISPUTEROUNDDURATIONINSECONDS412(bool _initial) public view returns (uint256); //inject NONSTANDARD NAMING function GETORCREATEDISPUTEWINDOWBYTIMESTAMP65(uint256 _timestamp, bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATECURRENTDISPUTEWINDOW813(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATENEXTDISPUTEWINDOW682(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATEPREVIOUSDISPUTEWINDOW575(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETOPENINTERESTINATTOCASH866() public view returns (uint256); //inject NONSTANDARD NAMING function GETTARGETREPMARKETCAPINATTOCASH438() public view returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEVALIDITYBOND873() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEDESIGNATEDREPORTSTAKE630() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEDESIGNATEDREPORTNOSHOWBOND936() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEMARKETREPBOND533() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEREPORTINGFEEDIVISOR44() public returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTETHRESHOLDFORFORK42() public view returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTETHRESHOLDFORDISPUTEPACING311() public view returns (uint256); //inject NONSTANDARD NAMING function GETINITIALREPORTMINVALUE947() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING function GETREPORTINGFEEDIVISOR13() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGCHILDPAYOUTNUMERATOR599(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function ISOPENINTERESTCASH47(address) public view returns (bool); //inject NONSTANDARD NAMING function ISFORKINGMARKET534() public view returns (bool); //inject NONSTANDARD NAMING function GETCURRENTDISPUTEWINDOW862(bool _initial) public view returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETDISPUTEWINDOWSTARTTIMEANDDURATION802(uint256 _timestamp, bool _initial) public view returns (uint256, uint256); //inject NONSTANDARD NAMING function ISPARENTOF319(IUniverse _shadyChild) public view returns (bool); //inject NONSTANDARD NAMING function UPDATETENTATIVEWINNINGCHILDUNIVERSE89(bytes32 _parentPayoutDistributionHash) public returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORMARKET856(IMarket _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING function MIGRATEMARKETOUT672(IUniverse _destinationUniverse) public returns (bool); //inject NONSTANDARD NAMING function MIGRATEMARKETIN285(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool); //inject NONSTANDARD NAMING function DECREMENTOPENINTEREST834(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function DECREMENTOPENINTERESTFROMMARKET346(IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function INCREMENTOPENINTEREST645(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function GETWINNINGCHILDUNIVERSE709() public view returns (IUniverse); //inject NONSTANDARD NAMING function ISFORKING853() public view returns (bool); //inject NONSTANDARD NAMING function DEPOSIT693(address _sender, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING function WITHDRAW474(address _recipient, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING function CREATESCALARMARKET875(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket); //inject NONSTANDARD NAMING } contract IV2ReputationToken is IReputationToken { function PARENTUNIVERSE976() external returns (IUniverse); //inject NONSTANDARD NAMING function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool); //inject NONSTANDARD NAMING function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool); //inject NONSTANDARD NAMING } library Reporting { uint256 private constant designated_reporting_duration_seconds939 = 1 days; //inject NONSTANDARD NAMING uint256 private constant dispute_round_duration_seconds351 = 7 days; //inject NONSTANDARD NAMING uint256 private constant initial_dispute_round_duration_seconds185 = 1 days; //inject NONSTANDARD NAMING uint256 private constant dispute_window_buffer_seconds655 = 1 hours; //inject NONSTANDARD NAMING uint256 private constant fork_duration_seconds463 = 60 days; //inject NONSTANDARD NAMING uint256 private constant base_market_duration_maximum20 = 30 days; // A market of 30 day length can always be created //inject NONSTANDARD NAMING uint256 private constant upgrade_cadence254 = 365 days; //inject NONSTANDARD NAMING uint256 private constant initial_upgrade_timestamp605 = 1627776000; // Aug 1st 2021 //inject NONSTANDARD NAMING uint256 private constant initial_rep_supply507 = 11 * 10 ** 6 * 10 ** 18; // 11 Million REP //inject NONSTANDARD NAMING uint256 private constant affiliate_source_cut_divisor194 = 5; // The trader gets 20% of the affiliate fee when an affiliate fee is taken //inject NONSTANDARD NAMING uint256 private constant default_validity_bond803 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING uint256 private constant validity_bond_floor708 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING uint256 private constant default_reporting_fee_divisor809 = 10000; // .01% fees //inject NONSTANDARD NAMING uint256 private constant maximum_reporting_fee_divisor548 = 10000; // Minimum .01% fees //inject NONSTANDARD NAMING uint256 private constant minimum_reporting_fee_divisor749 = 3; // Maximum 33.3~% fees. Note than anything less than a value of 2 here will likely result in bugs such as divide by 0 cases. //inject NONSTANDARD NAMING uint256 private constant target_invalid_markets_divisor747 = 100; // 1% of markets are expected to be invalid //inject NONSTANDARD NAMING uint256 private constant target_incorrect_designated_report_markets_divisor83 = 100; // 1% of markets are expected to have an incorrect designate report //inject NONSTANDARD NAMING uint256 private constant target_designated_report_no_shows_divisor678 = 20; // 5% of markets are expected to have a no show //inject NONSTANDARD NAMING uint256 private constant target_rep_market_cap_multiplier475 = 5; // We multiply and divide by constants since we may want to multiply by a fractional amount //inject NONSTANDARD NAMING uint256 private constant fork_threshold_divisor49 = 40; // 2.5% of the total REP supply being filled in a single dispute bond will trigger a fork //inject NONSTANDARD NAMING uint256 private constant maximum_dispute_rounds529 = 20; // We ensure that after 20 rounds of disputes a fork will occur //inject NONSTANDARD NAMING uint256 private constant minimum_slow_rounds438 = 8; // We ensure that at least 8 dispute rounds take DISPUTE_ROUND_DURATION_SECONDS+ seconds to complete until the next round begins //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTINGDURATIONSECONDS10() internal pure returns (uint256) { return designated_reporting_duration_seconds939; } //inject NONSTANDARD NAMING function GETINITIALDISPUTEROUNDDURATIONSECONDS286() internal pure returns (uint256) { return initial_dispute_round_duration_seconds185; } //inject NONSTANDARD NAMING function GETDISPUTEWINDOWBUFFERSECONDS683() internal pure returns (uint256) { return dispute_window_buffer_seconds655; } //inject NONSTANDARD NAMING function GETDISPUTEROUNDDURATIONSECONDS187() internal pure returns (uint256) { return dispute_round_duration_seconds351; } //inject NONSTANDARD NAMING function GETFORKDURATIONSECONDS842() internal pure returns (uint256) { return fork_duration_seconds463; } //inject NONSTANDARD NAMING function GETBASEMARKETDURATIONMAXIMUM759() internal pure returns (uint256) { return base_market_duration_maximum20; } //inject NONSTANDARD NAMING function GETUPGRADECADENCE338() internal pure returns (uint256) { return upgrade_cadence254; } //inject NONSTANDARD NAMING function GETINITIALUPGRADETIMESTAMP486() internal pure returns (uint256) { return initial_upgrade_timestamp605; } //inject NONSTANDARD NAMING function GETDEFAULTVALIDITYBOND656() internal pure returns (uint256) { return default_validity_bond803; } //inject NONSTANDARD NAMING function GETVALIDITYBONDFLOOR634() internal pure returns (uint256) { return validity_bond_floor708; } //inject NONSTANDARD NAMING function GETTARGETINVALIDMARKETSDIVISOR906() internal pure returns (uint256) { return target_invalid_markets_divisor747; } //inject NONSTANDARD NAMING function GETTARGETINCORRECTDESIGNATEDREPORTMARKETSDIVISOR444() internal pure returns (uint256) { return target_incorrect_designated_report_markets_divisor83; } //inject NONSTANDARD NAMING function GETTARGETDESIGNATEDREPORTNOSHOWSDIVISOR524() internal pure returns (uint256) { return target_designated_report_no_shows_divisor678; } //inject NONSTANDARD NAMING function GETTARGETREPMARKETCAPMULTIPLIER935() internal pure returns (uint256) { return target_rep_market_cap_multiplier475; } //inject NONSTANDARD NAMING function GETMAXIMUMREPORTINGFEEDIVISOR201() internal pure returns (uint256) { return maximum_reporting_fee_divisor548; } //inject NONSTANDARD NAMING function GETMINIMUMREPORTINGFEEDIVISOR230() internal pure returns (uint256) { return minimum_reporting_fee_divisor749; } //inject NONSTANDARD NAMING function GETDEFAULTREPORTINGFEEDIVISOR804() internal pure returns (uint256) { return default_reporting_fee_divisor809; } //inject NONSTANDARD NAMING function GETINITIALREPSUPPLY859() internal pure returns (uint256) { return initial_rep_supply507; } //inject NONSTANDARD NAMING function GETAFFILIATESOURCECUTDIVISOR779() internal pure returns (uint256) { return affiliate_source_cut_divisor194; } //inject NONSTANDARD NAMING function GETFORKTHRESHOLDDIVISOR823() internal pure returns (uint256) { return fork_threshold_divisor49; } //inject NONSTANDARD NAMING function GETMAXIMUMDISPUTEROUNDS774() internal pure returns (uint256) { return maximum_dispute_rounds529; } //inject NONSTANDARD NAMING function GETMINIMUMSLOWROUNDS218() internal pure returns (uint256) { return minimum_slow_rounds438; } //inject NONSTANDARD NAMING } contract IAugurTrading { function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING function LOGPROFITLOSSCHANGED911(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERCREATED154(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERCANCELED389(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERFILLED166(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETVOLUMECHANGED635(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool); //inject NONSTANDARD NAMING function LOGZEROXORDERFILLED898(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool); //inject NONSTANDARD NAMING function LOGZEROXORDERCANCELED137(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public; //inject NONSTANDARD NAMING } contract IOrders { function SAVEORDER165(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId); //inject NONSTANDARD NAMING function REMOVEORDER407(bytes32 _orderId) external returns (bool); //inject NONSTANDARD NAMING function GETMARKET927(bytes32 _orderId) public view returns (IMarket); //inject NONSTANDARD NAMING function GETORDERTYPE39(bytes32 _orderId) public view returns (Order.Types); //inject NONSTANDARD NAMING function GETOUTCOME167(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETAMOUNT930(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETPRICE598(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERCREATOR755(bytes32 _orderId) public view returns (address); //inject NONSTANDARD NAMING function GETORDERSHARESESCROWED20(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERMONEYESCROWED161(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERDATAFORCANCEL357(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address); //inject NONSTANDARD NAMING function GETORDERDATAFORLOGS935(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data); //inject NONSTANDARD NAMING function GETBETTERORDERID822(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING function GETWORSEORDERID439(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING function GETBESTORDERID727(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING function GETWORSTORDERID835(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING function GETLASTOUTCOMEPRICE593(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERID157(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32); //inject NONSTANDARD NAMING function GETTOTALESCROWED463(IMarket _market) public view returns (uint256); //inject NONSTANDARD NAMING function ISBETTERPRICE274(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING function ISWORSEPRICE692(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING function ASSERTISNOTBETTERPRICE18(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); //inject NONSTANDARD NAMING function ASSERTISNOTWORSEPRICE875(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); //inject NONSTANDARD NAMING function RECORDFILLORDER693(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool); //inject NONSTANDARD NAMING function SETPRICE687(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); //inject NONSTANDARD NAMING } library Order { using SafeMathUint256 for uint256; enum Types { Bid, Ask } enum TradeDirections { Long, Short } struct Data { // Contracts IMarket market; IAugur augur; IAugurTrading augurTrading; IShareToken shareToken; ICash cash; // Order bytes32 id; address creator; uint256 outcome; Order.Types orderType; uint256 amount; uint256 price; uint256 sharesEscrowed; uint256 moneyEscrowed; bytes32 betterOrderId; bytes32 worseOrderId; } function CREATE815(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) { //inject NONSTANDARD NAMING require(_outcome < _market.GETNUMBEROFOUTCOMES636(), "Order.create: Outcome is not within market range"); require(_price != 0, "Order.create: Price may not be 0"); require(_price < _market.GETNUMTICKS752(), "Order.create: Price is outside of market range"); require(_attoshares > 0, "Order.create: Cannot use amount of 0"); require(_creator != address(0), "Order.create: Creator is 0x0"); IShareToken _shareToken = IShareToken(_augur.LOOKUP594("ShareToken")); return Data({ market: _market, augur: _augur, augurTrading: _augurTrading, shareToken: _shareToken, cash: ICash(_augur.LOOKUP594("Cash")), id: 0, creator: _creator, outcome: _outcome, orderType: _type, amount: _attoshares, price: _price, sharesEscrowed: 0, moneyEscrowed: 0, betterOrderId: _betterOrderId, worseOrderId: _worseOrderId }); } // // "public" functions // function GETORDERID157(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) { //inject NONSTANDARD NAMING if (_orderData.id == bytes32(0)) { bytes32 _orderId = CALCULATEORDERID856(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed); require(_orders.GETAMOUNT930(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible"); _orderData.id = _orderId; } return _orderData.id; } function CALCULATEORDERID856(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed)); } function GETORDERTRADINGTYPEFROMMAKERDIRECTION100(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask; } function GETORDERTRADINGTYPEFROMFILLERDIRECTION800(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid; } function SAVEORDER165(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) { //inject NONSTANDARD NAMING GETORDERID157(_orderData, _orders); uint256[] memory _uints = new uint256[](5); _uints[0] = _orderData.amount; _uints[1] = _orderData.price; _uints[2] = _orderData.outcome; _uints[3] = _orderData.moneyEscrowed; _uints[4] = _orderData.sharesEscrowed; bytes32[] memory _bytes32s = new bytes32[](4); _bytes32s[0] = _orderData.betterOrderId; _bytes32s[1] = _orderData.worseOrderId; _bytes32s[2] = _tradeGroupId; _bytes32s[3] = _orderData.id; return _orders.SAVEORDER165(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator); } } interface IUniswapV2Pair { event APPROVAL665(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER723(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME524() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL582() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS958() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY304() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF492(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE377(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE293(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER644(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM669(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR256() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH256() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES605(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT866(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT159(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN674(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP992( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC856(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY585() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY704() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0151() external view returns (address); //inject NONSTANDARD NAMING function TOKEN132() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES901() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST708() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST245() external view returns (uint); //inject NONSTANDARD NAMING function KLAST943() external view returns (uint); //inject NONSTANDARD NAMING function MINT146(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN234(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP505(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM81(address to) external; //inject NONSTANDARD NAMING function SYNC86() external; //inject NONSTANDARD NAMING function INITIALIZE90(address, address) external; //inject NONSTANDARD NAMING } contract IRepSymbol { function GETREPSYMBOL498(address _augur, address _universe) external view returns (string memory); //inject NONSTANDARD NAMING } contract ReputationToken is VariableSupplyToken, IV2ReputationToken { using SafeMathUint256 for uint256; string constant public name600 = "Reputation"; //inject NONSTANDARD NAMING IUniverse internal universe; IUniverse public parentUniverse; uint256 internal totalMigrated; IERC20 public legacyRepToken; IAugur public augur; address public warpSync; constructor(IAugur _augur, IUniverse _universe, IUniverse _parentUniverse) public { augur = _augur; universe = _universe; parentUniverse = _parentUniverse; warpSync = _augur.LOOKUP594("WarpSync"); legacyRepToken = IERC20(_augur.LOOKUP594("LegacyReputationToken")); require(warpSync != address(0)); require(legacyRepToken != IERC20(0)); } function SYMBOL582() public view returns (string memory) { //inject NONSTANDARD NAMING return IRepSymbol(augur.LOOKUP594("RepSymbol")).GETREPSYMBOL498(address(augur), address(universe)); } function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(_attotokens > 0); IUniverse _destinationUniverse = universe.CREATECHILDUNIVERSE712(_payoutNumerators); IReputationToken _destination = _destinationUniverse.GETREPUTATIONTOKEN35(); BURN234(msg.sender, _attotokens); _destination.MIGRATEIN692(msg.sender, _attotokens); return true; } function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING IUniverse _parentUniverse = parentUniverse; require(ReputationToken(msg.sender) == _parentUniverse.GETREPUTATIONTOKEN35()); require(augur.GETTIMESTAMP626() < _parentUniverse.GETFORKENDTIME510()); MINT146(_reporter, _attotokens); totalMigrated += _attotokens; // Update the fork tentative winner and finalize if we can if (!_parentUniverse.GETFORKINGMARKET637().ISFINALIZED623()) { _parentUniverse.UPDATETENTATIVEWINNINGCHILDUNIVERSE89(universe.GETPARENTPAYOUTDISTRIBUTIONHASH230()); } return true; } function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool) { //inject NONSTANDARD NAMING IReportingParticipant _reportingParticipant = IReportingParticipant(msg.sender); require(parentUniverse.ISCONTAINERFORREPORTINGPARTICIPANT696(_reportingParticipant)); // simulate a 40% ROI which would have occured during a normal dispute had this participant's outcome won the dispute uint256 _bonus = _amountMigrated.MUL760(2) / 5; MINT146(address(_reportingParticipant), _bonus); return true; } function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool) { //inject NONSTANDARD NAMING require(warpSync == msg.sender); MINT146(_target, _amountToMint); universe.UPDATEFORKVALUES73(); return true; } function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender))); BURN234(msg.sender, _amountToBurn); return true; } function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(IUniverse(msg.sender) == universe); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function ASSERTREPUTATIONTOKENISLEGITCHILD164(IReputationToken _shadyReputationToken) private view { //inject NONSTANDARD NAMING IUniverse _universe = _shadyReputationToken.GETUNIVERSE719(); require(universe.ISPARENTOF319(_universe)); require(_universe.GETREPUTATIONTOKEN35() == _shadyReputationToken); } function GETUNIVERSE719() public view returns (IUniverse) { //inject NONSTANDARD NAMING return universe; } function GETTOTALMIGRATED220() public view returns (uint256) { //inject NONSTANDARD NAMING return totalMigrated; } function GETLEGACYREPTOKEN110() public view returns (IERC20) { //inject NONSTANDARD NAMING return legacyRepToken; } function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 _totalSupply = totalSupply; if (parentUniverse == IUniverse(0)) { return _totalSupply.ADD571(legacyRepToken.TOTALSUPPLY304()).SUB692(legacyRepToken.BALANCEOF492(address(1))).SUB692(legacyRepToken.BALANCEOF492(address(0))); } else if (augur.GETTIMESTAMP626() >= parentUniverse.GETFORKENDTIME510()) { return _totalSupply; } else { return _totalSupply + parentUniverse.GETREPUTATIONTOKEN35().GETTOTALTHEORETICALSUPPLY552(); } } function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSTRANSFERRED904(universe, _from, _to, _value, balances[_from], balances[_to]); } function ONMINT315(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSMINTED985(universe, _target, _amount, totalSupply, balances[_target]); } function ONBURN653(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSBURNED995(universe, _target, _amount, totalSupply, balances[_target]); } function MIGRATEFROMLEGACYREPUTATIONTOKEN918() public returns (bool) { //inject NONSTANDARD NAMING require(parentUniverse == IUniverse(0)); uint256 _legacyBalance = legacyRepToken.BALANCEOF492(msg.sender); require(legacyRepToken.TRANSFERFROM669(msg.sender, address(1), _legacyBalance)); MINT146(msg.sender, _legacyBalance); return true; } }
inject NONSTANDARD NAMING
function DESIGNATEDREPORTERNOSHOWBONDTOTAL703() external view returns (uint256);
2,553,892
pragma solidity ^0.4.20; // Solidity compiler version supported by Azure Blockchain Workbench //--------------------------------------------- //Generated automatically for application 'RefrigeratedTransportation' by AppCodeGen utility //--------------------------------------------- import "./RefrigeratedTransportation.sol"; contract WorkbenchBase { event WorkbenchContractCreated(string applicationName, string workflowName, address originatingAddress); event WorkbenchContractUpdated(string applicationName, string workflowName, string action, address originatingAddress); string internal ApplicationName; string internal WorkflowName; function WorkbenchBase(string applicationName, string workflowName) public { ApplicationName = applicationName; WorkflowName = workflowName; } function ContractCreated() public { WorkbenchContractCreated(ApplicationName, WorkflowName, msg.sender); } function ContractUpdated(string action) public { WorkbenchContractUpdated(ApplicationName, WorkflowName, action, msg.sender); } } // // The wrapper contract RefrigeratedTransportation_AzureBlockchainWorkBench invokes functions from RefrigeratedTransportation. // The inheritance order of RefrigeratedTransportation_AzureBlockchainWorkBench ensures that functions and variables in RefrigeratedTransportation // are not shadowed by WorkbenchBase. // Any access of WorkbenchBase function or variables is qualified with WorkbenchBase // contract RefrigeratedTransportation_AzureBlockchainWorkBench is WorkbenchBase, RefrigeratedTransportation { // // Constructor // function RefrigeratedTransportation_AzureBlockchainWorkBench(address device, address supplyChainOwner, address supplyChainObserver, int256 minHumidity, int256 maxHumidity, int256 minTemperature, int256 maxTemperature) WorkbenchBase("RefrigeratedTransportation", "RefrigeratedTransportation") RefrigeratedTransportation(device, supplyChainOwner, supplyChainObserver, minHumidity, maxHumidity, minTemperature, maxTemperature) public { // Check postconditions and access control for constructor of RefrigeratedTransportation // Constructor should transition the state to StartState assert(State == StateType.Created); // Signals successful creation of contract RefrigeratedTransportation WorkbenchBase.ContractCreated(); } //////////////////////////////////////////// // Workbench Transitions // // Naming convention of transition functions: // Transition_<CurrentState>_Number_<TransitionNumberFromCurrentState>_<FunctionNameOnTransition> // Transition function arguments same as underlying function // ////////////////////////////////////////////// function Transition_Created_Number_0_TransferResponsibility (address newCounterparty) public { // Transition preconditions require(State == StateType.Created); require(msg.sender == InitiatingCounterparty); // Call overridden function TransferResponsibility in this contract TransferResponsibility(newCounterparty); // Transition postconditions assert(State == StateType.InTransit); } function Transition_Created_Number_1_IngestTelemetry (int256 humidity, int256 temperature, int256 timestamp) public { // Transition preconditions require(State == StateType.Created); require(msg.sender == Device); // Call overridden function IngestTelemetry in this contract IngestTelemetry(humidity, temperature, timestamp); // Transition postconditions assert(State == StateType.OutOfCompliance || State == StateType.Created); } function Transition_InTransit_Number_0_TransferResponsibility (address newCounterparty) public { // Transition preconditions require(State == StateType.InTransit); require(msg.sender == Counterparty); // Call overridden function TransferResponsibility in this contract TransferResponsibility(newCounterparty); // Transition postconditions assert(State == StateType.InTransit); } function Transition_InTransit_Number_1_IngestTelemetry (int256 humidity, int256 temperature, int256 timestamp) public { // Transition preconditions require(State == StateType.InTransit); require(msg.sender == Device); // Call overridden function IngestTelemetry in this contract IngestTelemetry(humidity, temperature, timestamp); // Transition postconditions assert(State == StateType.OutOfCompliance || State == StateType.InTransit); } function Transition_InTransit_Number_2_Complete () public { // Transition preconditions require(State == StateType.InTransit); require(msg.sender == Owner); // Call overridden function Complete in this contract Complete(); // Transition postconditions assert(State == StateType.Completed); } function IngestTelemetry(int256 humidity, int256 temperature, int256 timestamp) public { // Placeholder for function preconditions // Call function IngestTelemetry of RefrigeratedTransportation RefrigeratedTransportation.IngestTelemetry(humidity, temperature, timestamp); // Placeholder for function postconditions // Signals successful execution of function IngestTelemetry WorkbenchBase.ContractUpdated("IngestTelemetry"); } function TransferResponsibility(address newCounterparty) public { // Placeholder for function preconditions // Call function TransferResponsibility of RefrigeratedTransportation RefrigeratedTransportation.TransferResponsibility(newCounterparty); // Placeholder for function postconditions // Signals successful execution of function TransferResponsibility WorkbenchBase.ContractUpdated("TransferResponsibility"); } function Complete() public { // Placeholder for function preconditions // Call function Complete of RefrigeratedTransportation RefrigeratedTransportation.Complete(); // Placeholder for function postconditions // Signals successful execution of function Complete WorkbenchBase.ContractUpdated("Complete"); } }
Transition preconditions Call overridden function TransferResponsibility in this contract Transition postconditions
function Transition_InTransit_Number_0_TransferResponsibility (address newCounterparty) public { require(State == StateType.InTransit); require(msg.sender == Counterparty); TransferResponsibility(newCounterparty); assert(State == StateType.InTransit); }
5,533,606
pragma solidity >=0.4.21 <0.7.0; import "./Account.sol"; contract Spy { using SafeMath for uint; Account accountInstance; constructor(address _account_address) public { accountInstance = Account(_account_address); } mapping (address => uint) public numOfSpy; mapping (address => uint) public levelOfSpy; mapping (address => uint) public ownerStartCreateTime; mapping (address => uint) public ownerCreateSpyTime; mapping (address => uint) public ownerStartUpgradeTime; mapping (address => uint) public ownerUpgradeSpyTime; uint public createSpyTime = 10; uint public UpgradeSpyTime = 10; uint public spyHealth = 1; uint public spyPower = 1; uint public spyFrequency = 1; uint public spyArmour = 1; uint public spyCapacity = 1; uint public spySpeed = 1; function setSpyLevel(address _owner, uint value) public { levelOfSpy[_owner] = value; } function setStartCreateTime(address _owner, uint value) public { ownerStartCreateTime[_owner] = value; } function setCreateSpyTime(address _owner, uint value) public { ownerCreateSpyTime[_owner] = value; } function setStartUpgradeTime(address _owner, uint value) public { ownerStartUpgradeTime[_owner] = value; } function setUpgradeSpyTime(address _owner, uint value) public { ownerUpgradeSpyTime[_owner] = value; } function setNumOfSpy(address _owner, uint value) public { numOfSpy[_owner] = value; } function _updateSpyPower(address _owner) public { // power[_owner] = numOfSpy[_owner] * levelOfSpy[_owner]; accountInstance.setUserSpyPower(_owner, numOfSpy[_owner] * levelOfSpy[_owner]); } function _createSpy(address _owner, uint number) public returns(bool) { uint foodCost = (25* levelOfSpy[_owner] - 5) * number; uint ironCost = (25* levelOfSpy[_owner] - 5) * number; uint coinCost = (25* levelOfSpy[_owner] - 5) * number; return accountInstance.cost(_owner, foodCost, uint(0), ironCost, uint(0), coinCost); } function _UpgradeSpy(address _owner) public returns(bool){ uint foodCost = 500* levelOfSpy[_owner] - 125; uint ironCost = 500* levelOfSpy[_owner] - 125; uint coinCost = 500* levelOfSpy[_owner] - 125; levelOfSpy[_owner] += 1; return accountInstance.cost(_owner, foodCost, uint(0), ironCost, uint(0), coinCost); } function getSpyAmount(address _owner) public view returns(uint) { return numOfSpy[_owner]; } function _spy(address myCastle, address attackedCastle) public view returns(bool) { address winner; address loser; bool win; //bool win = -1; if (accountInstance.getUserSpyPower(myCastle) > accountInstance.getUserSpyPower(attackedCastle)){ winner = myCastle; loser = attackedCastle; win = true; } else { winner = attackedCastle; loser = myCastle; win = false; } return win; } function sendSpy(uint _ownerId, uint _attackedCastleId) public view returns(bool) { //require(msg.sender == accountInstance.convertCastleToOwner(_ownerId)); address myCastle = accountInstance.convertCastleToOwner(_ownerId); address attackedCastle = accountInstance.convertCastleToOwner(_attackedCastleId); //returns TRUE if spy of myCastle > attackedCastle return _spy(myCastle, attackedCastle); } // return 0 if failed (maybe already creating or not enough resource) otherwise return createtime function startCreateSpy(uint number) public returns(uint) { address _owner = msg.sender; if(ownerStartCreateTime[_owner] != 0) return uint(0); // check if there is already creating spys bool enoughResource; uint lvOfSpy; enoughResource = _createSpy(_owner, number); lvOfSpy = levelOfSpy[_owner]; if(enoughResource == false) return uint(0); setStartCreateTime(_owner, uint(now)); setCreateSpyTime(_owner, createSpyTime * lvOfSpy * number); return ownerCreateSpyTime[_owner]; } function getCreateSpyTime() public view returns(uint, uint, uint) { return ( ownerStartCreateTime[msg.sender], uint(now) - ownerStartCreateTime[msg.sender], ownerCreateSpyTime[msg.sender] ) ; } // // return 0 if success else return remaining time function updateCreateSpy(address _owner) public returns(uint) { if (ownerStartCreateTime[_owner] == 0) return 0; if (uint(now) >= ownerStartCreateTime[_owner].add(ownerCreateSpyTime[_owner])) { uint num; num = ownerCreateSpyTime[_owner].div( levelOfSpy[_owner].mul(createSpyTime) ); setNumOfSpy(_owner, numOfSpy[_owner] + (num)); setStartCreateTime(_owner, 0); setCreateSpyTime(_owner, 0); _updateSpyPower(_owner); return 0; } else { uint remainingTime = (ownerStartCreateTime[_owner] + ownerCreateSpyTime[_owner]).sub(uint(now)); return remainingTime; } } }
return 0 if failed (maybe already creating or not enough resource) otherwise return createtime
function startCreateSpy(uint number) public returns(uint) { address _owner = msg.sender; bool enoughResource; uint lvOfSpy; enoughResource = _createSpy(_owner, number); lvOfSpy = levelOfSpy[_owner]; if(enoughResource == false) return uint(0); setStartCreateTime(_owner, uint(now)); setCreateSpyTime(_owner, createSpyTime * lvOfSpy * number); return ownerCreateSpyTime[_owner]; }
13,118,916
pragma solidity 0.5.16; /** * @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 () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } 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); } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title SafeMath96 * @dev Unsigned math operations with safety checks that revert on error with 96 bit unsiged integer */ library SafeMath96 { function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title CHN interface * @dev see https://github.com/chain/chain-token/blob/main/ChainToken.sol */ interface CHNInterface { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function burn(uint256 _value) external; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Burn(address indexed burner, 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 _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { address private MINT_BASE_TOKEN; uint256 private MAX_SUPPLY_AMOUNT; constructor (address mintBaseToken, uint256 MAX_SUPPLY) public { MINT_BASE_TOKEN = mintBaseToken; MAX_SUPPLY_AMOUNT = MAX_SUPPLY; } /** * @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 returns (bool) { require(CHNInterface(MINT_BASE_TOKEN).balanceOf(msg.sender) >= value, "Mint Base Token Insufficient"); require(totalSupply().add(value.mul(1000)) < MAX_SUPPLY_AMOUNT, "Mint limited max supply"); IERC20(MINT_BASE_TOKEN).transferFrom(msg.sender, address(this), value); CHNInterface(MINT_BASE_TOKEN).burn(value); _mint(to, value.mul(1000)); return true; } } /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } contract Chain is ERC20Mintable, ERC20Detailed { using SafeMath96 for uint96; uint8 public constant DECIMALS = 18; uint256 public constant INITIAL_SUPPLY = 21537311000 * (10 ** uint256(DECIMALS)); uint256 public constant MAX_SUPPLY = 68895442185 * (10 ** uint256(DECIMALS)); address public constant MINT_BASE = 0x41C37A4683d6a05adB31c39D71348A8403B13Ca9; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor () public ERC20Detailed("Chain", "XCN", DECIMALS) ERC20Mintable(MINT_BASE, MAX_SUPPLY) { _mint(msg.sender, INITIAL_SUPPLY); } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); _moveDelegates(delegates[msg.sender], delegates[to], value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, allowance(from, msg.sender).sub(value)); _moveDelegates(delegates[msg.sender], delegates[to], value); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Xcn::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Xcn::delegateBySig: invalid nonce"); require(now <= expiry, "Xcn::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint256) { require(blockNumber < block.number, "Xcn::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal { uint32 blockNumber = safe32(block.number, "Xcn::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
Function to mint tokens to The address that will receive the minted tokens. value The amount of tokens to mint. return A boolean that indicates if the operation was successful./
function mint(address to, uint256 value) public returns (bool) { require(CHNInterface(MINT_BASE_TOKEN).balanceOf(msg.sender) >= value, "Mint Base Token Insufficient"); require(totalSupply().add(value.mul(1000)) < MAX_SUPPLY_AMOUNT, "Mint limited max supply"); IERC20(MINT_BASE_TOKEN).transferFrom(msg.sender, address(this), value); CHNInterface(MINT_BASE_TOKEN).burn(value); _mint(to, value.mul(1000)); return true; }
12,035,635
./full_match/43113/0xFFD36482CFf7a98a3A16b9852aD8594da42b14c2/sources/contracts/hola.sol
public/Private - el view es para que se aloje localmente y no se vaya al resto de los nodos
function consultarFrase() public view returns(string memory){ return frase; }
7,149,038
./full_match/111000/0x42104e0985aE238ba603D30b52c36c666759700C/sources/contracts/CHARITY_WALLET.sol
Sends coins to the specified recipient address recipientAddress The address to send coins to amount The amount of coins to send/
function sendCoins(address payable recipientAddress, uint256 amount) external whenNotPaused onlyRole(MANAGER_ROLE) { bool success; require(amount > 0,"Can not send zero amount"); require(address(this).balance >= amount, "Balance is too low"); require(success, "Transfer failed."); emit CoinsSent(recipientAddress, amount); }
16,365,911
pragma solidity 0.4.21; // File: contracts/ExchangeHandler.sol /// @title Interface for all exchange handler contracts interface ExchangeHandler { /// @dev Get the available amount left to fill for an order /// @param orderAddresses Array of address values needed for this DEX order /// @param orderValues Array of uint values needed for this DEX order /// @param exchangeFee Value indicating the fee for this DEX order /// @param v ECDSA signature parameter v /// @param r ECDSA signature parameter r /// @param s ECDSA signature parameter s /// @return Available amount left to fill for this order function getAvailableAmount( address[8] orderAddresses, uint256[6] orderValues, uint256 exchangeFee, uint8 v, bytes32 r, bytes32 s ) external returns (uint256); /// @dev Perform a buy order at the exchange /// @param orderAddresses Array of address values needed for each DEX order /// @param orderValues Array of uint values needed for each DEX order /// @param exchangeFee Value indicating the fee for this DEX order /// @param amountToFill Amount to fill in this order /// @param v ECDSA signature parameter v /// @param r ECDSA signature parameter r /// @param s ECDSA signature parameter s /// @return Amount filled in this order function performBuy( address[8] orderAddresses, uint256[6] orderValues, uint256 exchangeFee, uint256 amountToFill, uint8 v, bytes32 r, bytes32 s ) external payable returns (uint256); /// @dev Perform a sell order at the exchange /// @param orderAddresses Array of address values needed for each DEX order /// @param orderValues Array of uint values needed for each DEX order /// @param exchangeFee Value indicating the fee for this DEX order /// @param amountToFill Amount to fill in this order /// @param v ECDSA signature parameter v /// @param r ECDSA signature parameter r /// @param s ECDSA signature parameter s /// @return Amount filled in this order function performSell( address[8] orderAddresses, uint256[6] orderValues, uint256 exchangeFee, uint256 amountToFill, uint8 v, bytes32 r, bytes32 s ) external returns (uint256); } // File: contracts/WETH9.sol // Copyright (C) 2015, 2016, 2017 Dapphub // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; Deposit(msg.sender, msg.value); } function withdraw(uint wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint) { return this.balance; } function approve(address guy, uint wad) public returns (bool) { allowance[msg.sender][guy] = wad; Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; Transfer(src, dst, wad); return true; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/AirSwapHandler.sol /** * @title AirSwap interface. */ interface AirSwapInterface { /// @dev Mapping of order hash to bool (true = already filled). function fills( bytes32 hash ) external view returns (bool); /// @dev Fills an order by transferring tokens between (maker or escrow) and taker. /// Maker is given tokenA to taker. function fill( address makerAddress, uint makerAmount, address makerToken, address takerAddress, uint takerAmount, address takerToken, uint256 expiration, uint256 nonce, uint8 v, bytes32 r, bytes32 s ) external payable; } /** * @title AirSwap wrapper contract. * @dev Assumes makers and takers have approved this contract to access their balances. */ contract AirSwapHandler is ExchangeHandler, Ownable { /// @dev AirSwap exhange address AirSwapInterface public airSwap; WETH9 public weth; address public totle; uint256 constant MAX_UINT = 2**256 - 1; modifier onlyTotle() { require(msg.sender == totle); _; } /// @dev Constructor function AirSwapHandler( address _airSwap, address _wethAddress, address _totle ) public { require(_airSwap != address(0x0)); require(_wethAddress != address(0x0)); require(_totle != address(0x0)); airSwap = AirSwapInterface(_airSwap); weth = WETH9(_wethAddress); totle = _totle; } /// @dev Get the available amount left to fill for an order /// @param orderValues Array of uint values needed for this DEX order /// @return Available amount left to fill for this order function getAvailableAmount( address[8], uint256[6] orderValues, uint256, uint8, bytes32, bytes32 ) external returns (uint256) { return orderValues[1]; } /// @dev Perform a buy order at the exchange /// @param orderAddresses Array of address values needed for each DEX order /// @param orderValues Array of uint values needed for each DEX order /// @param amountToFill Amount to fill in this order /// @param v ECDSA signature parameter v /// @param r ECDSA signature parameter r /// @param s ECDSA signature parameter s /// @return Amount filled in this order function performBuy( address[8] orderAddresses, uint256[6] orderValues, uint256, uint256 amountToFill, uint8 v, bytes32 r, bytes32 s ) external onlyTotle payable returns (uint256) { return fillBuy(orderAddresses, orderValues, v, r, s); } /// @dev Perform a sell order at the exchange /// @param orderAddresses Array of address values needed for each DEX order /// @param orderValues Array of uint values needed for each DEX order /// @param amountToFill Amount to fill in this order /// @param v ECDSA signature parameter v /// @param r ECDSA signature parameter r /// @param s ECDSA signature parameter s /// @return Amount filled in this order function performSell( address[8] orderAddresses, uint256[6] orderValues, uint256, uint256 amountToFill, uint8 v, bytes32 r, bytes32 s ) external onlyTotle returns (uint256) { return fillSell(orderAddresses, orderValues, v, r, s); } function setTotle(address _totle) external onlyOwner { require(_totle != address(0)); totle = _totle; } /// @dev The contract is not designed to hold and/or manage tokens. /// Withdraws token in the case of emergency. Only an owner is allowed to call this. function withdrawToken(address _token, uint _amount) external onlyOwner returns (bool) { return ERC20(_token).transfer(owner, _amount); } /// @dev The contract is not designed to hold ETH. /// Withdraws ETH in the case of emergency. Only an owner is allowed to call this. function withdrawETH(uint _amount) external onlyOwner returns (bool) { owner.transfer(_amount); } function approveToken(address _token, uint amount) external onlyOwner { require(ERC20(_token).approve(address(airSwap), amount)); } function() public payable { } /** Validates order arguments for fill() and cancel() functions. */ function validateOrder( address makerAddress, uint makerAmount, address makerToken, address takerAddress, uint takerAmount, address takerToken, uint256 expiration, uint256 nonce) public view returns (bool) { // Hash arguments to identify the order. bytes32 hashV = keccak256(makerAddress, makerAmount, makerToken, takerAddress, takerAmount, takerToken, expiration, nonce); return airSwap.fills(hashV); } /// orderAddresses[0] == makerAddress /// orderAddresses[1] == makerToken /// orderAddresses[2] == takerAddress /// orderAddresses[3] == takerToken /// orderValues[0] = makerAmount /// orderValues[1] = takerAmount /// orderValues[2] = expiration /// orderValues[3] = nonce function fillBuy( address[8] orderAddresses, uint256[6] orderValues, uint8 v, bytes32 r, bytes32 s ) private returns (uint) { airSwap.fill.value(msg.value)(orderAddresses[0], orderValues[0], orderAddresses[1], address(this), orderValues[1], orderAddresses[3], orderValues[2], orderValues[3], v, r, s); require(validateOrder(orderAddresses[0], orderValues[0], orderAddresses[1], address(this), orderValues[1], orderAddresses[3], orderValues[2], orderValues[3])); require(ERC20(orderAddresses[1]).transfer(orderAddresses[2], orderValues[0])); return orderValues[0]; } /// orderAddresses[0] == makerAddress /// orderAddresses[1] == makerToken /// orderAddresses[2] == takerAddress /// orderAddresses[3] == takerToken /// orderValues[0] = makerAmount /// orderValues[1] = takerAmount /// orderValues[2] = expiration /// orderValues[3] = nonce function fillSell( address[8] orderAddresses, uint256[6] orderValues, uint8 v, bytes32 r, bytes32 s ) private returns (uint) { assert(msg.sender == totle); require(orderAddresses[1] == address(weth)); uint takerAmount = orderValues[1]; if(ERC20(orderAddresses[3]).allowance(address(this), address(airSwap)) == 0) { require(ERC20(orderAddresses[3]).approve(address(airSwap), MAX_UINT)); } airSwap.fill(orderAddresses[0], orderValues[0], orderAddresses[1], address(this), takerAmount, orderAddresses[3], orderValues[2], orderValues[3], v, r, s); require(validateOrder(orderAddresses[0], orderValues[0], orderAddresses[1], address(this), takerAmount, orderAddresses[3], orderValues[2], orderValues[3])); weth.withdraw(orderValues[0]); msg.sender.transfer(orderValues[0]); return orderValues[0]; } }
Perform a buy order at the exchange orderAddresses Array of address values needed for each DEX order orderValues Array of uint values needed for each DEX order amountToFill Amount to fill in this order v ECDSA signature parameter v r ECDSA signature parameter r s ECDSA signature parameter s return Amount filled in this order
function performBuy( address[8] orderAddresses, uint256[6] orderValues, uint256, uint256 amountToFill, uint8 v, bytes32 r, bytes32 s ) external onlyTotle payable returns (uint256) { return fillBuy(orderAddresses, orderValues, v, r, s); }
6,532,134
./partial_match/1/0x4d74c068129C1DB1216FaB1b28b9C050908C577B/sources/contracts/AvoForwarder.sol
Retrieves the current avoNonce of AvocadoMultisig for `owner_` address. Needed for signatures. owner_ Avocado owner to retrieve the nonce for. index_ index number of Avocado for `owner_` EOA return returns the avoNonce for the `owner_` necessary to sign a meta transaction
function avoNonce(address owner_, uint32 index_) external view returns (uint256) { address avoAddress_ = _computeAvocado(owner_, index_); if (Address.isContract(avoAddress_)) { return IAvocadoMultisigV1(avoAddress_).avoNonce(); } return 0; }
15,730,471
./full_match/3/0xe8476FB89c76CE2Ad16877FD7e746Bc2db6FE627/sources/broker.sol
convert the account argument from address to bytes. create an in-memory fixed-size bytes array. declare variable types. get the capitalized characters in the actual checksum. iterate over bytes, processing left and right nibble in each iteration. locate the byte and extract each nibble. locate and extract each capitalization status. get the offset from nibble value to ascii character for left nibble. add the converted character to the byte array. get the offset from nibble value to ascii character for right nibble. add the converted character to the byte array.
function addressToString( address account ) public pure returns (string memory asciiString) { bytes20 data = bytes20(account); bytes memory asciiBytes = new bytes(40); uint8 b; uint8 leftNibble; uint8 rightNibble; bool leftCaps; bool rightCaps; uint8 asciiOffset; bool[40] memory caps = _toChecksumCapsFlags(account); for (uint256 i = 0; i < data.length; i++) { b = uint8(uint160(data) / (2 ** (8 * (19 - i)))); leftNibble = b / 16; rightNibble = b - 16 * leftNibble; leftCaps = caps[2 * i]; rightCaps = caps[2 * i + 1]; asciiOffset = _getAsciiOffset(leftNibble, leftCaps); asciiBytes[2 * i] = bytes1(leftNibble + asciiOffset); asciiOffset = _getAsciiOffset(rightNibble, rightCaps); asciiBytes[2 * i + 1] = bytes1(rightNibble + asciiOffset); } return string(abi.encodePacked("0x", asciiBytes)); }
8,269,832
pragma solidity ^0.4.17; import "zeppelin-solidity/contracts/ECRecovery.sol"; import "zeppelin-solidity/contracts/MerkleProof.sol"; import "zeppelin-solidity/contracts/math/SafeMath.sol"; library JobLib { using SafeMath for uint256; // Prefix hashed with message hash when a signature is produced by the eth_sign RPC call string constant PERSONAL_HASH_PREFIX = "\u0019Ethereum Signed Message:\n32"; // # of bytes used to store a video profile identifier as a utf8 encoded string // Video profile identifier is currently stored as bytes4(keccak256(PROFILE_NAME)) // We use 2 * 4 = 8 bytes because we store the bytes in a utf8 encoded string so // the identifiers can be easily parsed off-chain uint8 constant VIDEO_PROFILE_SIZE = 8; /* * @dev Checks if a transcoding options string is valid * A transcoding options string is composed of video profile ids so its length * must be a multiple of VIDEO_PROFILE_SIZE * @param _transcodingOptions Transcoding options string */ function validTranscodingOptions(string _transcodingOptions) public pure returns (bool) { uint256 transcodingOptionsLength = bytes(_transcodingOptions).length; return transcodingOptionsLength > 0 && transcodingOptionsLength % VIDEO_PROFILE_SIZE == 0; } /* * @dev Computes the amount of fees given total segments, total number of profiles and price per segment * @param _totalSegments # of segments * @param _transcodingOptions String containing video profiles for a job * @param _pricePerSegment Price in LPT base units per segment */ function calcFees(uint256 _totalSegments, string _transcodingOptions, uint256 _pricePerSegment) public pure returns (uint256) { // Calculate total profiles defined in the transcoding options string uint256 totalProfiles = bytes(_transcodingOptions).length.div(VIDEO_PROFILE_SIZE); return _totalSegments.mul(totalProfiles).mul(_pricePerSegment); } /* * Computes whether a segment is eligible for verification based on the last call to claimWork() * @param _segmentNumber Sequence number of segment in stream * @param _segmentRange Range of segments claimed * @param _challengeBlock Block afer the block when claimWork() was called * @param _challengeBlockHash Block hash of challenge block * @param _verificationRate Rate at which a particular segment should be verified */ function shouldVerifySegment( uint256 _segmentNumber, uint256[2] _segmentRange, uint256 _challengeBlock, bytes32 _challengeBlockHash, uint64 _verificationRate ) public pure returns (bool) { // Segment must be in segment range if (_segmentNumber < _segmentRange[0] || _segmentNumber > _segmentRange[1]) { return false; } // Use block hash and block number of the block after a claim to determine if a segment // should be verified if (uint256(keccak256(_challengeBlock, _challengeBlockHash, _segmentNumber)) % _verificationRate == 0) { return true; } else { return false; } } /* * @dev Checks if a segment was signed by a broadcaster address * @param _streamId Stream ID for the segment * @param _segmentNumber Sequence number of segment in the stream * @param _dataHash Hash of segment data * @param _broadcasterSig Broadcaster signature over h(streamId, segmentNumber, dataHash) * @param _broadcaster Broadcaster address */ function validateBroadcasterSig( string _streamId, uint256 _segmentNumber, bytes32 _dataHash, bytes _broadcasterSig, address _broadcaster ) public pure returns (bool) { return ECRecovery.recover(personalSegmentHash(_streamId, _segmentNumber, _dataHash), _broadcasterSig) == _broadcaster; } /* * @dev Checks if a transcode receipt hash was included in a committed merkle root * @param _streamId StreamID for the segment * @param _segmentNumber Sequence number of segment in the stream * @param _dataHash Hash of segment data * @param _transcodedDataHash Hash of transcoded segment data * @param _broadcasterSig Broadcaster signature over h(streamId, segmentNumber, dataHash) * @param _broadcaster Broadcaster address */ function validateReceipt( string _streamId, uint256 _segmentNumber, bytes32 _dataHash, bytes32 _transcodedDataHash, bytes _broadcasterSig, bytes _proof, bytes32 _claimRoot ) public pure returns (bool) { return MerkleProof.verifyProof(_proof, _claimRoot, transcodeReceiptHash(_streamId, _segmentNumber, _dataHash, _transcodedDataHash, _broadcasterSig)); } /* * Compute the hash of a segment * @param _streamId Stream identifier * @param _segmentSequenceNumber Segment sequence number in stream * @param _dataHash Content-addressed storage hash of segment data */ function segmentHash(string _streamId, uint256 _segmentNumber, bytes32 _dataHash) public pure returns (bytes32) { return keccak256(_streamId, _segmentNumber, _dataHash); } /* * @dev Compute the personal segment hash of a segment. Hashes the concatentation of the personal hash prefix and the segment hash * @param _streamId Stream identifier * @param _segmentSequenceNumber Segment sequence number in stream * @param _dataHash Content-addrssed storage hash of segment data */ function personalSegmentHash(string _streamId, uint256 _segmentNumber, bytes32 _dataHash) public pure returns (bytes32) { bytes memory prefixBytes = bytes(PERSONAL_HASH_PREFIX); return keccak256(prefixBytes, segmentHash(_streamId, _segmentNumber, _dataHash)); } /* * Compute the hash of a transcode receipt * @param _streamId Stream identifier * @param _segmentSequenceNumber Segment sequence number in stream * @param _dataHash Content-addressed storage hash of segment data * @param _transcodedDataHash Content-addressed storage hash of transcoded segment data * @param _broadcasterSig Broadcaster's signature over segment */ function transcodeReceiptHash( string _streamId, uint256 _segmentNumber, bytes32 _dataHash, bytes32 _transcodedDataHash, bytes _broadcasterSig ) public pure returns (bytes32) { return keccak256(_streamId, _segmentNumber, _dataHash, _transcodedDataHash, _broadcasterSig); } }
Computes the amount of fees given total segments, total number of profiles and price per segment _totalSegments of segments _transcodingOptions String containing video profiles for a job _pricePerSegment Price in LPT base units per segment/ Calculate total profiles defined in the transcoding options string
function calcFees(uint256 _totalSegments, string _transcodingOptions, uint256 _pricePerSegment) public pure returns (uint256) { uint256 totalProfiles = bytes(_transcodingOptions).length.div(VIDEO_PROFILE_SIZE); return _totalSegments.mul(totalProfiles).mul(_pricePerSegment); }
5,463,672
pragma solidity ^0.4.15; import "zeppelin-solidity/contracts/crowdsale/Crowdsale.sol"; import "zeppelin-solidity/contracts/crowdsale/CappedCrowdsale.sol"; import "zeppelin-solidity/contracts/token/MintableToken.sol"; import "zeppelin-solidity/contracts/token/StandardToken.sol"; // import "./InitialDistribution.sol"; import "./MyFinalizableCrowdsale.sol"; import "./MultiCappedCrowdsale.sol"; import "./MyCrowdsaleToken.sol"; /** * @title MySale * @dev This is a sale with the following features: * - erc20 based * - Soft cap and hidden hard cap * - When finished distributes percent to specific address based on whether the * cap was reached. * - Start and end block for the ico * - Sends incoming eth to a specific address */ contract MySale is MyFinalizableCrowdsale, MultiCappedCrowdsale { // how many token units a buyer gets per wei uint256 public presaleRate; uint256 public postSoftRate; uint256 public postHardRate; uint256 public presaleEndTime; function MySale(uint256 _startTime, uint256 _endTime, uint256 _presaleEndTime, uint256 _rate, uint256 _rateDiff, uint256 _softCap, address _wallet, bytes32 _hardCapHash, address _tokenWallet, uint256 _endBuffer) MultiCappedCrowdsale(_softCap, _hardCapHash, _endBuffer) MyFinalizableCrowdsale(_tokenWallet) Crowdsale(_startTime, _endTime, _rate, _wallet) { presaleRate = _rate+_rateDiff; postSoftRate = _rate-_rateDiff; postHardRate = _rate-(2*_rateDiff); presaleEndTime = _presaleEndTime; // InitialDistribution.initialDistribution(token); } // Allows generating tokens for externally funded participants (other blockchains) function pregenTokens(address beneficiary, uint256 weiAmount, uint256 tokenAmount) external onlyOwner { require(beneficiary != 0x0); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokenAmount); TokenPurchase(msg.sender, beneficiary, weiAmount, tokenAmount); } // Overrides Crowdsale function function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; uint256 currentRate = rate; if (block.timestamp < presaleEndTime) { currentRate = presaleRate; } else if (hardCap > 0 && weiRaised > hardCap) { currentRate = postHardRate; } else if (weiRaised > softCap) { currentRate = postSoftRate; } // calculate token amount to be created uint256 tokens = weiAmount.mul(currentRate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // Overrides Crowdsale function function createTokenContract() internal returns (MintableToken) { return new MyCrowdsaleToken(); } // Overrides MyFinalizableSale function function finalization() internal { if (weiRaised < softCap) { generateFinalTokens(1000); } else if (weiRaised < hardCap) { generateFinalTokens(666); } else { generateFinalTokens(428); } token.finishMinting(); super.finalization(); } /* Make sure no eth funds become stuck on contract */ function withdraw(uint256 weiValue) onlyOwner { wallet.transfer(weiValue); } }
Overrides Crowdsale function
function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; uint256 currentRate = rate; if (block.timestamp < presaleEndTime) { currentRate = presaleRate; } else if (hardCap > 0 && weiRaised > hardCap) { currentRate = postHardRate; } else if (weiRaised > softCap) { currentRate = postSoftRate; } token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); }
6,439,278
./full_match/97/0xA2bE9B9637A2E235f28552FC168f4e65cD0Ca1dc/sources/project_/contracts/diamond/libraries/LibAlpManager.sol
It is not allowed for the value of any token in the LP to become negative after burning. ∵ alpPrice_ > 0 ∴ (LibVault.getTotalValueUsd() + lpUnPnlUsd) > 0
function _calculateTokenAmount(LibVault.AvailableToken memory at, uint256 alpAmount) private view returns (uint256 amountOut) { require(at.tokenAddress != address(0), "LibAlpManager: Token does not exist"); (int256 lpUnPnlUsd, int256 lpTokenUnPnlUsd) = ITradingCore(address(this)).lpUnrealizedPnlUsd(at.tokenAddress); int256 totalValueUsd = LibVault.getTotalValueUsd() + lpUnPnlUsd; uint256 alpPrice_ = _alpPrice(totalValueUsd); require(alpPrice_ > 0, "LibAlpManager: ALP Price is not available"); (uint256 tokenOutPrice,) = IPriceFacade(address(this)).getPriceFromCacheOrOracle(at.tokenAddress); int256 poolTokenOutUsd = int256(LibVault.vaultStorage().treasury[at.tokenAddress] * tokenOutPrice * 1e10 / (10 ** at.decimals)) + lpTokenUnPnlUsd; uint256 amountOutUsd = alpPrice_ * alpAmount / 1e8; require(poolTokenOutUsd >= int256(amountOutUsd), "LibAlpManager: tokenOut balance is insufficient"); uint256 afterTaxAmountOutUsd = amountOutUsd * (1e4 - _getFeePoint(at, uint256(totalValueUsd), poolTokenOutUsd, amountOutUsd, false)) / 1e4; require(int256(afterTaxAmountOutUsd) <= LibVault.maxWithdrawAbleUsd(totalValueUsd), "LibAlpManager: tokenOut balance is insufficient"); return afterTaxAmountOutUsd * (10 ** at.decimals) / (tokenOutPrice * 1e10); }
5,026,521
./full_match/44787/0xB39A777c6E3AE43e630621bC144Ce9bd6DcC344e/sources/src/SwayAdmin.sol
access control pausable
function __SwayAdmin_init(address governor) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); __Pausable_init_unchained(); __SwayAdmin_init_unchained(governor); }
13,242,760
/** *Submitted for verification at Etherscan.io on 2021-05-24 */ /** *Submitted for verification at Bscscan.com on 2020-09-09 */ pragma solidity 0.5.16; interface IHRC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract BCSS is Context, IHRC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint8 public _decimals; string public _symbol; string public _name; constructor() public { _name = "BCSS Token"; _symbol = "BCSS"; _decimals = 18; _totalSupply = 100000000 * 1e18; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev See {HRC20-totalSupply}. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev See {HRC20-balanceOf}. */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @dev See {HRC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {HRC20-allowance}. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {HRC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {HRC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {HRC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "HRC20: 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 {HRC20-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 {HRC20-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, "HRC20: decreased allowance below zero")); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ // function mint(uint256 amount) public onlyOwner returns (bool) { // _mint(_msgSender(), amount); // return true; // } // /** // * @dev Burn `amount` tokens and decreasing the total supply. // */ // function burn(uint256 amount) public returns (bool) { // _burn(_msgSender(), amount); // return true; // } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "HRC20: transfer from the zero address"); require(recipient != address(0), "HRC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "HRC20: 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), "HRC20: 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), "HRC20: burn from the zero address"); // _balances[account] = _balances[account].sub(amount, "HRC20: 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), "HRC20: approve from the zero address"); require(spender != address(0), "HRC20: 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, "HRC20: burn amount exceeds allowance")); // } }
See {HRC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {HRC20}; Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for `sender`'s tokens of at least `amount`./
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "HRC20: transfer amount exceeds allowance")); return true; }
10,772,887
pragma solidity ^0.4.22; // File: contracts/ERC223/ERC223_receiving_contract.sol /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data); } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/ERC223/ERC223.sol /** * @title Reference implementation of the ERC223 standard token. */ contract ERC223 is StandardToken { event Transfer(address indexed from, address indexed to, uint value, bytes data); /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public returns (bool) { bytes memory empty; return transfer(_to, _value, empty); } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data Optional metadata. */ function transfer(address _to, uint _value, bytes _data) public returns (bool) { super.transfer(_to, _value); if (isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); } return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public returns (bool) { bytes memory empty; return transferFrom(_from, _to, _value, empty); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amount of tokens to be transferred * @param _data Optional metadata. */ function transferFrom(address _from, address _to, uint _value, bytes _data) public returns (bool) { super.transferFrom(_from, _to, _value); if (isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(_from, _value, _data); } Transfer(_from, _to, _value, _data); return true; } function isContract(address _addr) private view returns (bool) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: zeppelin-solidity/contracts/token/ERC20/CappedToken.sol /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; function CappedToken(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: contracts/RootsToken.sol contract RootsToken is CappedToken, ERC223 { string constant public name = "ROOTS Token"; string constant public symbol = "ROOTS"; uint constant public decimals = 18; function RootsToken() public CappedToken(1e10 * 1e18) {} function mintlist(address[] _to, uint256[] _amount) onlyOwner canMint public { require(_to.length == _amount.length); for (uint256 i = 0; i < _to.length; i++) { mint(_to[i], _amount[i]); } } }
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint the amount of tokens to be transferred/
function transferFrom(address _from, address _to, uint _value) public returns (bool) { bytes memory empty; return transferFrom(_from, _to, _value, empty); }
393,671
/** * Created on 2018-06-05 16:37 * @summary: Our NFT Minting Contract which inherits ERC721 capability from LSNFT * @author: Fazri Zubair & Farhan Khwaja */ pragma solidity ^0.4.23; pragma solidity ^0.4.23; /* NFT Metadata Schema { "title": "Asset Metadata", "type": "object", "properties": { "name": { "type": "string", "description": "Identifies the asset to which this NFT represents", }, "description": { "type": "string", "description": "Describes the asset to which this NFT represents", }, "image": { "type": "string", "description": "A URI pointing to a resource with mime type image/* representing the asset to which this NFT represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive.", } } } */ /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 public constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require (ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require (isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require (_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require (owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require (_to != owner); require (msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require (_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require (_from != address(0)); require (_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require (checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require (_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require (ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require (tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require (ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } /** * @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,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 public constant ERC721_RECEIVED = 0x150b7a02; /** * @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,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } contract ERC721Holder is ERC721Receiver { function onERC721Received( address, address, uint256, bytes ) public returns(bytes4) { return ERC721_RECEIVED; } } /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Base Server Address for Token MetaData URI string internal tokenURIBase; /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @notice The user/developper needs to add the tokenID, in the end of URL, to * use the URI and get all details. Ex. www.<apiURL>.com/token/<tokenID> * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require (exists(_tokenId)); return tokenURIBase; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require (_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require (_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _uri string URI to assign */ function _setTokenURIBase(string _uri) internal { tokenURIBase = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array ownedTokens[_from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7; /* bytes4(keccak256(&#39;supportsInterface(bytes4)&#39;)); */ bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63; /* bytes4(keccak256(&#39;totalSupply()&#39;)) ^ bytes4(keccak256(&#39;tokenOfOwnerByIndex(address,uint256)&#39;)) ^ bytes4(keccak256(&#39;tokenByIndex(uint256)&#39;)); */ bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f; /* bytes4(keccak256(&#39;name()&#39;)) ^ bytes4(keccak256(&#39;symbol()&#39;)) ^ bytes4(keccak256(&#39;tokenURI(uint256)&#39;)); */ bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd; /* bytes4(keccak256(&#39;balanceOf(address)&#39;)) ^ bytes4(keccak256(&#39;ownerOf(uint256)&#39;)) ^ bytes4(keccak256(&#39;approve(address,uint256)&#39;)) ^ bytes4(keccak256(&#39;getApproved(uint256)&#39;)) ^ bytes4(keccak256(&#39;setApprovalForAll(address,bool)&#39;)) ^ bytes4(keccak256(&#39;isApprovedForAll(address,address)&#39;)) ^ bytes4(keccak256(&#39;transferFrom(address,address,uint256)&#39;)) ^ bytes4(keccak256(&#39;safeTransferFrom(address,address,uint256)&#39;)) ^ bytes4(keccak256(&#39;safeTransferFrom(address,address,uint256,bytes)&#39;)); */ bytes4 public constant InterfaceSignature_ERC721Optional =- 0x4f558e79; /* bytes4(keccak256(&#39;exists(uint256)&#39;)); */ /** * @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). * @dev Returns true for any standardized interfaces implemented by this contract. * @param _interfaceID bytes4 the interface to check for * @return true for any standardized interfaces implemented by this contract. */ function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721) || (_interfaceID == InterfaceSignature_ERC721Enumerable) || (_interfaceID == InterfaceSignature_ERC721Metadata)); } function implementsERC721() public pure returns (bool) { return true; } } /* Lucid Sight, Inc. ERC-721 Collectibles. * @title LSNFT - Lucid Sight, Inc. Non-Fungible Token * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract LSNFT is ERC721Token { /*** EVENTS ***/ /// @dev The Created event is fired whenever a new collectible comes into existence. event Created(address owner, uint256 tokenId); /*** DATATYPES ***/ struct NFT { // The sequence of potential attributes a Collectible has and can provide in creation events. Used in Creation logic to spwan new Cryptos uint256 attributes; // Current Game Card identifier uint256 currentGameCardId; // MLB Game Identifier (if asset generated as a game reward) uint256 mlbGameId; // player orverride identifier uint256 playerOverrideId; // official MLB Player ID uint256 mlbPlayerId; // earnedBy : In some instances we may want to retroactively write which MLB player triggered // the event that created a Legendary Trophy. This optional field should be able to be written // to after generation if we determine an event was newsworthy enough uint256 earnedBy; // asset metadata uint256 assetDetails; // Attach/Detach Flag uint256 isAttached; } NFT[] allNFTs; function isLSNFT() public view returns (bool) { return true; } /// For creating NFT function _createNFT ( uint256[5] _nftData, address _owner, uint256 _isAttached) internal returns(uint256) { NFT memory _lsnftObj = NFT({ attributes : _nftData[1], currentGameCardId : 0, mlbGameId : _nftData[2], playerOverrideId : _nftData[3], assetDetails: _nftData[0], isAttached: _isAttached, mlbPlayerId: _nftData[4], earnedBy: 0 }); uint256 newLSNFTId = allNFTs.push(_lsnftObj) - 1; _mint(_owner, newLSNFTId); // Created event emit Created(_owner, newLSNFTId); return newLSNFTId; } /// @dev Gets attributes of NFT function _getAttributesOfToken(uint256 _tokenId) internal returns(NFT) { NFT storage lsnftObj = allNFTs[_tokenId]; return lsnftObj; } function _approveForSale(address _owner, address _to, uint256 _tokenId) internal { address owner = ownerOf(_tokenId); require (_to != owner); require (_owner == owner || isApprovedForAll(owner, _owner)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(_owner, _to, _tokenId); } } } /** 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); /// @dev 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 only to Managers */ modifier onlyManager() { require (msg.sender == managerPrimary || msg.sender == managerSecondary); _; } /** * @dev Operation modifiers for limiting access to only Banker */ modifier onlyBanker() { require (msg.sender == bankManager); _; } /** * @dev Operation modifiers for any Operators */ modifier anyOperator() { require ( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); _; } /** * @dev Operation modifier for any Other Manager */ modifier onlyOtherManagers() { require (otherManagers[msg.sender] == 1); _; } /** * @dev Assigns a new address to act as the Primary Manager. * @param _newGM New primary manager address */ function setPrimaryManager(address _newGM) external onlyManager { require (_newGM != address(0)); managerPrimary = _newGM; } /** * @dev Assigns a new address to act as the Secondary Manager. * @param _newGM New Secondary Manager Address */ function setSecondaryManager(address _newGM) external onlyManager { require (_newGM != address(0)); managerSecondary = _newGM; } /** * @dev Assigns a new address to act as the Banker. * @param _newBK New Banker Address */ function setBanker(address _newBK) external onlyManager { require (_newBK != address(0)); bankManager = _newBK; } /// @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; } /*** 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 */ function unpause() public onlyManager whenPaused { // can&#39;t unpause if contract was upgraded paused = false; } /** * @dev Errors out the contract thus mkaing the contract non-functionable */ function hasError() public onlyManager whenPaused { error = true; } /** * @dev Removes the Error Hold from the contract and resumes it for working */ function noError() public onlyManager whenPaused { error = false; } } /** Base contract for DodgersNFT Collectibles. Holds all commons, events and base variables. * @title Lucid Sight MLB NFT 2018 * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract CollectibleBase is LSNFT { /*** EVENTS ***/ /// @dev Event emitted when an attribute of the player is updated event AssetUpdated(uint256 tokenId); /*** STORAGE ***/ /// @dev A mapping of Team Id to Team Sequence Number to Collectible mapping (uint256 => mapping (uint32 => uint256) ) public nftTeamIdToSequenceIdToCollectible; /// @dev A mapping from Team IDs to the Sequqence Number . mapping (uint256 => uint32) public nftTeamIndexToCollectibleCount; /// @dev Array to hold details on attachment for each LS NFT Collectible mapping(uint256 => uint256[]) public nftCollectibleAttachments; /// @dev Mapping to control the asset generation per season. mapping(uint256 => uint256) public generationSeasonController; /// @dev Mapping for generation Season Dict. mapping(uint256 => uint256) public generationSeasonDict; /// @dev internal function to update player override id function _updatePlayerOverrideId(uint256 _tokenId, uint256 _newPlayerOverrideId) internal { // Get Token Obj NFT storage lsnftObj = allNFTs[_tokenId]; lsnftObj.playerOverrideId = _newPlayerOverrideId; // Update Token Data with new updated attributes allNFTs[_tokenId] = lsnftObj; emit AssetUpdated(_tokenId); } /** * @dev An internal method that helps in generation of new NFT Collectibles * @param _teamId teamId of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _isAttached State of the asset (attached or dettached) * @param _nftData Array of data required for creation */ function _createNFTCollectible( uint8 _teamId, uint256 _attributes, address _owner, uint256 _isAttached, uint256[5] _nftData ) internal returns (uint256) { uint256 generationSeason = (_attributes % 1000000).div(1000); require (generationSeasonController[generationSeason] == 1); uint32 _sequenceId = getSequenceId(_teamId); uint256 newNFTCryptoId = _createNFT(_nftData, _owner, _isAttached); nftTeamIdToSequenceIdToCollectible[_teamId][_sequenceId] = newNFTCryptoId; nftTeamIndexToCollectibleCount[_teamId] = _sequenceId; return newNFTCryptoId; } function getSequenceId(uint256 _teamId) internal returns (uint32) { return (nftTeamIndexToCollectibleCount[_teamId] + 1); } /** * @dev Internal function, Helps in updating the Creation Stop Time * @param _season Season UINT Code * @param _value 0 - Not allowed, 1 - Allowed */ function _updateGenerationSeasonFlag(uint256 _season, uint8 _value) internal { generationSeasonController[_season] = _value; } /** @param _owner The owner whose ships tokens we are interested in. * @dev This method MUST NEVER be called by smart contract code. First, it&#39;s fairly * expensive (it walks the entire Collectibles owners array looking for NFT belonging to owner) */ function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalItems = balanceOf(_owner); uint256 resultIndex = 0; // We count on the fact that all Collectible have IDs starting at 0 and increasing // sequentially up to the total count. uint256 _assetId; for (_assetId = 0; _assetId < totalItems; _assetId++) { result[resultIndex] = tokenOfOwnerByIndex(_owner,_assetId); resultIndex++; } return result; } } /// @dev internal function to update MLB player id function _updateMLBPlayerId(uint256 _tokenId, uint256 _newMLBPlayerId) internal { // Get Token Obj NFT storage lsnftObj = allNFTs[_tokenId]; lsnftObj.mlbPlayerId = _newMLBPlayerId; // Update Token Data with new updated attributes allNFTs[_tokenId] = lsnftObj; emit AssetUpdated(_tokenId); } /// @dev internal function to update asset earnedBy value for an asset/token function _updateEarnedBy(uint256 _tokenId, uint256 _earnedBy) internal { // Get Token Obj NFT storage lsnftObj = allNFTs[_tokenId]; lsnftObj.earnedBy = _earnedBy; // Update Token Data with new updated attributes allNFTs[_tokenId] = lsnftObj; emit AssetUpdated(_tokenId); } } /* Handles creating new Collectibles for promo and seed. * @title CollectibleMinting Minting * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) * Inspired and adapted from KittyCore.sol created by Axiom Zen * Ref: ETH Contract - 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d */ contract CollectibleMinting is CollectibleBase, OperationalControl { uint256 public rewardsRedeemed = 0; /// @dev Counts the number of promo collectibles that can be made per-team uint256[31] public promoCreatedCount; /// @dev Counts the number of seed collectibles that can be made in total uint256 public seedCreatedCount; /// @dev Bool to toggle batch support bool public isBatchSupported = true; /// @dev A mapping of contracts that can trigger functions mapping (address => bool) public contractsApprovedList; /** * @dev Helps to toggle batch supported flag * @param _flag The flag */ function updateBatchSupport(bool _flag) public onlyManager { isBatchSupported = _flag; } modifier canCreate() { require (contractsApprovedList[msg.sender] || msg.sender == managerPrimary || msg.sender == managerSecondary); _; } /** * @dev Add an address to the Approved List * @param _newAddress The new address to be approved for interaction with the contract */ function addToApproveList(address _newAddress) public onlyManager { require (!contractsApprovedList[_newAddress]); contractsApprovedList[_newAddress] = true; } /** * @dev Remove an address from Approved List * @param _newAddress The new address to be approved for interaction with the contract */ function removeFromApproveList(address _newAddress) public onlyManager { require (contractsApprovedList[_newAddress]); delete contractsApprovedList[_newAddress]; } /** * @dev Generates promo collectibles. Only callable by Game Master, with isAttached as 0. * @notice The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createPromoCollectible( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } if(allNFTs.length > 0) { promoCreatedCount[_teamId]++; } uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData); } /** * @dev Generaes a new single seed Collectible, with isAttached as 0. * @notice Helps in creating seed collectible.The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createSeedCollectible( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } seedCreatedCount++; uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData); } /** * @dev Generate new Reward Collectible and transfer it to the owner, with isAttached as 0. * @notice Helps in redeeming the Rewards using our Oracle. Creates & transfers the asset to the redeemer (_owner) * The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner (redeemer) of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createRewardCollectible ( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } rewardsRedeemed++; uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData); } /** * @dev Generate new ETH Card Collectible, with isAttached as 2. * @notice Helps to generate Collectibles/Tokens/Asset and transfer to ETH Cards, * which can be redeemed using our web-app.The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createETHCardCollectible ( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } rewardsRedeemed++; uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 2, _nftData); } } /* @title Interface for DodgersNFT Contract * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract SaleManager { function createSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _owner) external; } /** * DodgersNFT manages all aspects of the Lucid Sight, Inc. CryptoBaseball. * @title DodgersNFT * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract DodgersNFT is CollectibleMinting { /// @dev Set in case the DodgersNFT contract requires an upgrade address public newContractAddress; string public constant MLB_Legal = "Major League Baseball trademarks and copyrights are used with permission of the applicable MLB entity. All rights reserved."; // Time LS Oracle has to respond to detach requests uint32 public detachmentTime = 0; // Indicates if attached system is Active (Transfers will be blocked if attached and active) bool public attachedSystemActive; // Sale Manager Contract SaleManager public saleManagerAddress; /** * @dev DodgersNFT constructor. */ constructor() public { // Starts paused. paused = true; managerPrimary = msg.sender; managerSecondary = msg.sender; bankManager = msg.sender; name_ = "LucidSight-DODGERS-NFT"; symbol_ = "DNFTCB"; } /** * @dev Sets the address for the NFT Contract * @param _saleManagerAddress The nft address */ function setSaleManagerAddress(address _saleManagerAddress) public onlyManager { require (_saleManagerAddress != address(0)); saleManagerAddress = SaleManager(_saleManagerAddress); } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { uint256 isAttached = checkIsAttached(_tokenId); if(isAttached == 2) { //One-Time Auth for Physical Card Transfers require (msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); updateIsAttached(_tokenId, 0); } else if(attachedSystemActive == true && isAttached >= 1) { require (msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); } else { require (isApprovedOrOwner(msg.sender, _tokenId)); } _; } /** * @dev Used to mark the smart contract as upgraded, in case of a issue * @param _v2Address The new contract address */ function setNewAddress(address _v2Address) external onlyManager { require (_v2Address != address(0)); newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } /** * @dev Returns all the relevant information about a specific Collectible. * @notice Get details about your collectible * @param _tokenId The token identifier * @return isAttached Is Object attached * @return teamId team identifier of the asset/token/collectible * @return positionId position identifier of the asset/token/collectible * @return creationTime creation timestamp * @return attributes attribute of the asset/token/collectible * @return currentGameCardId current game card of the asset/token/collectible * @return mlbGameID mlb game identifier in which the asset/token/collectible was generated * @return playerOverrideId player override identifier of the asset/token/collectible * @return playerStatus status of the player (Rookie/Veteran/Historical) * @return playerHandedness handedness of the asset * @return mlbPlayerId official MLB Player Identifier */ function getCollectibleDetails(uint256 _tokenId) external view returns ( uint256 isAttached, uint32 sequenceId, uint8 teamId, uint8 positionId, uint64 creationTime, uint256 attributes, uint256 playerOverrideId, uint256 mlbGameId, uint256 currentGameCardId, uint256 mlbPlayerId, uint256 earnedBy, uint256 generationSeason ) { NFT memory obj = _getAttributesOfToken(_tokenId); attributes = obj.attributes; currentGameCardId = obj.currentGameCardId; mlbGameId = obj.mlbGameId; playerOverrideId = obj.playerOverrideId; mlbPlayerId = obj.mlbPlayerId; creationTime = uint64(obj.assetDetails); sequenceId = uint32(obj.assetDetails>>64); teamId = uint8(obj.assetDetails>>96); positionId = uint8(obj.assetDetails>>104); isAttached = obj.isAttached; earnedBy = obj.earnedBy; generationSeason = generationSeasonDict[(obj.attributes % 1000000) / 1000]; } /** * @dev This is public rather than external so we can call super.unpause * without using an expensive CALL. */ function unpause() public onlyManager { /// Actually unpause the contract. super.unpause(); } /** * @dev Helper function to get the teamID of a collectible.To avoid using getCollectibleDetails * @notice Returns the teamID associated with the asset/collectible/token * @param _tokenId The token identifier */ function getTeamId(uint256 _tokenId) external view returns (uint256) { NFT memory obj = _getAttributesOfToken(_tokenId); uint256 teamId = uint256(uint8(obj.assetDetails>>96)); return uint256(teamId); } /** * @dev Helper function to get the position of a collectible.To avoid using getCollectibleDetails * @notice Returns the position of the asset/collectible/token * @param _tokenId The token identifier */ function getPositionId(uint256 _tokenId) external view returns (uint256) { NFT memory obj = _getAttributesOfToken(_tokenId); uint256 positionId = uint256(uint8(obj.assetDetails>>104)); return positionId; } /** * @dev Helper function to get the game card. To avoid using getCollectibleDetails * @notice Returns the gameCard associated with the asset/collectible/token * @param _tokenId The token identifier */ function getGameCardId(uint256 _tokenId) public view returns (uint256) { NFT memory obj = _getAttributesOfToken(_tokenId); return obj.currentGameCardId; } /** * @dev Returns isAttached property value for an asset/collectible/token * @param _tokenId The token identifier */ function checkIsAttached(uint256 _tokenId) public view returns (uint256) { NFT memory obj = _getAttributesOfToken(_tokenId); return obj.isAttached; } /** * @dev Helper function to get the attirbute of the collectible.To avoid using getCollectibleDetails * @notice Returns the ability of an asset/collectible/token from attributes. * @param _tokenId The token identifier * @return ability ability of the asset */ function getAbilitiesForCollectibleId(uint256 _tokenId) external view returns (uint256 ability) { NFT memory obj = _getAttributesOfToken(_tokenId); uint256 _attributes = uint256(obj.attributes); ability = (_attributes % 1000); } /** * @dev Only allows trasnctions to go throught if the msg.sender is in the apporved list * @notice Updates the gameCardID properrty of the asset * @param _gameCardNumber The game card number * @param _playerId The player identifier */ function updateCurrentGameCardId(uint256 _gameCardNumber, uint256 _playerId) public whenNotPaused { require (contractsApprovedList[msg.sender]); NFT memory obj = _getAttributesOfToken(_playerId); obj.currentGameCardId = _gameCardNumber; if ( _gameCardNumber == 0 ) { obj.isAttached = 0; } else { obj.isAttached = 1; } allNFTs[_playerId] = obj; } /** * @dev Only Manager can add an attachment (special events) to the collectible * @notice Adds an attachment to collectible. * @param _tokenId The token identifier * @param _attachment The attachment */ function addAttachmentToCollectible ( uint256 _tokenId, uint256 _attachment) external onlyManager whenNotPaused { require (exists(_tokenId)); nftCollectibleAttachments[_tokenId].push(_attachment); emit AssetUpdated(_tokenId); } /** * @dev It will remove the attachment form the collectible. We will need to re-add all attachment(s) if removed. * @notice Removes all attachments from collectible. * @param _tokenId The token identifier */ function removeAllAttachmentsFromCollectible(uint256 _tokenId) external onlyManager whenNotPaused { require (exists(_tokenId)); delete nftCollectibleAttachments[_tokenId]; emit AssetUpdated(_tokenId); } /** * @notice Transfers the ownership of NFT from one address to another address * @dev responsible for gifting assets to other user. * @param _to to address * @param _tokenId The token identifier */ function giftAsset(address _to, uint256 _tokenId) public whenNotPaused { safeTransferFrom(msg.sender, _to, _tokenId); } /** * @dev responsible for setting the tokenURI. * @notice The user/developper needs to add the tokenID, in the end of URL, to * use the URI and get all details. Ex. www.<apiURL>.com/token/<tokenID> * @param _tokenURI The token uri */ function setTokenURIBase (string _tokenURI) public anyOperator { _setTokenURIBase(_tokenURI); } /** * @dev Allowed to be called by onlyGameManager to update a certain collectible playerOverrideID * @notice Sets the player override identifier. * @param _tokenId The token identifier * @param _newOverrideId The new player override identifier */ function setPlayerOverrideId(uint256 _tokenId, uint256 _newOverrideId) public onlyManager whenNotPaused { require (exists(_tokenId)); _updatePlayerOverrideId(_tokenId, _newOverrideId); } /** * @notice Updates the Generation Season Controller. * @dev Allowed to be called by onlyGameManager to update the generation season. * this helps to control the generation of collectible. * @param _season Season UINT representation * @param _value 0-Not allowed, 1-open, >=2 Locked Forever */ function updateGenerationStopTime(uint256 _season, uint8 _value ) public onlyManager whenNotPaused { require (generationSeasonController[_season] == 1 && _value != 0); _updateGenerationSeasonFlag(_season, _value); } /** * @dev set Generation Season Controller, can only be called by Managers._season can be [0,1,2,3..] and * _value can be [0,1,N]. * @notice _value of 1: means generation of collectible is allowed. anything, apart from 1, wont allow generating assets for that season. * @param _season Season UINT representation */ function setGenerationSeasonController(uint256 _season) public onlyManager whenNotPaused { require (generationSeasonController[_season] == 0); _updateGenerationSeasonFlag(_season, 1); } /** * @dev Adding value to DICT helps in showing the season value in getCollectibleDetails * @notice Updates the Generation Season Dict. * @param _season Season UINT representation * @param _value 0-Not allowed,1-allowed */ function updateGenerationDict(uint256 _season, uint64 _value) public onlyManager whenNotPaused { require (generationSeasonDict[_season] <= 1); generationSeasonDict[_season] = _value; } /** * @dev Helper function to avoid calling getCollectibleDetails * @notice Gets the MLB player Id from the player attributes * @param _tokenId The token identifier * @return playerId MLB Player Identifier */ function getPlayerId(uint256 _tokenId) external view returns (uint256 playerId) { NFT memory obj = _getAttributesOfToken(_tokenId); playerId = ((obj.attributes.div(100000000000000000)) % 1000); } /** * @dev Helper function to avoid calling getCollectibleDetails * @notice Gets the attachments for an asset * @param _tokenId The token identifier * @return attachments */ function getAssetAttachment(uint256 _tokenId) external view returns (uint256[]) { uint256[] _attachments = nftCollectibleAttachments[_tokenId]; uint256[] attachments; for(uint i=0;i<_attachments.length;i++){ attachments.push(_attachments[i]); } return attachments; } /** * @dev Can only be trigerred by Managers. Updates the earnedBy property of the NFT * @notice Helps in updating the earned _by property of an asset/token. * @param _tokenId asser/token identifier * @param _earnedBy New asset/token DNA */ function updateEarnedBy(uint256 _tokenId, uint256 _earnedBy) public onlyManager whenNotPaused { require (exists(_tokenId)); _updateEarnedBy(_tokenId, _earnedBy); } /** * @dev A batch function to facilitate batching of asset creation. canCreate modifier * helps in controlling who can call the function * @notice Batch Function to Create Assets * @param _teamId The team identifier * @param _attributes The attributes * @param _playerOverrideId The player override identifier * @param _mlbPlayerId The mlb player identifier * @param _to To Address */ function batchCreateAsset( uint8[] _teamId, uint256[] _attributes, uint256[] _playerOverrideId, uint256[] _mlbPlayerId, address[] _to) external canCreate whenNotPaused { require (isBatchSupported); require (_teamId.length > 0 && _attributes.length > 0 && _playerOverrideId.length > 0 && _mlbPlayerId.length > 0 && _to.length > 0); uint256 assetDetails; uint256[5] memory _nftData; for(uint ii = 0; ii < _attributes.length; ii++){ require (_to[ii] != address(0) && _teamId[ii] != 0 && _attributes.length != 0 && _mlbPlayerId[ii] != 0); assetDetails = uint256(uint64(now)); assetDetails |= uint256(getSequenceId(_teamId[ii]))<<64; assetDetails |= uint256(_teamId[ii])<<96; assetDetails |= uint256((_attributes[ii]/1000000000000000000000000000000000000000)-800)<<104; _nftData = [assetDetails, _attributes[ii], 0, _playerOverrideId[ii], _mlbPlayerId[ii]]; _createNFTCollectible(_teamId[ii], _attributes[ii], _to[ii], 0, _nftData); } } /** * @dev A batch function to facilitate batching of asset creation for ETH Cards. canCreate modifier * helps in controlling who can call the function * @notice Batch Function to Create Assets * @param _teamId The team identifier * @param _attributes The attributes * @param _playerOverrideId The player override identifier * @param _mlbPlayerId The mlb player identifier * @param _to { parameter_description } */ function batchCreateETHCardAsset( uint8[] _teamId, uint256[] _attributes, uint256[] _playerOverrideId, uint256[] _mlbPlayerId, address[] _to) external canCreate whenNotPaused { require (isBatchSupported); require (_teamId.length > 0 && _attributes.length > 0 && _playerOverrideId.length > 0 && _mlbPlayerId.length > 0 && _to.length > 0); uint256 assetDetails; uint256[5] memory _nftData; for(uint ii = 0; ii < _attributes.length; ii++){ require (_to[ii] != address(0) && _teamId[ii] != 0 && _attributes.length != 0 && _mlbPlayerId[ii] != 0); assetDetails = uint256(uint64(now)); assetDetails |= uint256(getSequenceId(_teamId[ii]))<<64; assetDetails |= uint256(_teamId[ii])<<96; assetDetails |= uint256((_attributes[ii]/1000000000000000000000000000000000000000)-800)<<104; _nftData = [assetDetails, _attributes[ii], 0, _playerOverrideId[ii], _mlbPlayerId[ii]]; _createNFTCollectible(_teamId[ii], _attributes[ii], _to[ii], 2, _nftData); } } /** * @dev Overriden TransferFrom, with the modifier canTransfer which uses our attachment system * @notice Helps in trasnferring assets * @param _from the address sending from * @param _to the address sending to * @param _tokenId The token identifier */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // Asset should not be in play require (checkIsAttached(_tokenId) == 0); require (_from != address(0)); require (_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Facilitates batch trasnfer of collectible with multiple TO Address, depending if batch is supported on contract. * @notice Batch Trasnfer with multpple TO addresses * @param _tokenIds The token identifiers * @param _fromB the address sending from * @param _toB the address sending to */ function multiBatchTransferFrom( uint256[] _tokenIds, address[] _fromB, address[] _toB) public { require (isBatchSupported); require (_tokenIds.length > 0 && _fromB.length > 0 && _toB.length > 0); uint256 _id; address _to; address _from; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0 && _fromB[i] != 0 && _toB[i] != 0); _id = _tokenIds[i]; _to = _toB[i]; _from = _fromB[i]; transferFrom(_from, _to, _id); } } /** * @dev Facilitates batch trasnfer of collectible, depending if batch is supported on contract * @notice Batch TransferFrom with the same to & from address * @param _tokenIds The asset identifiers * @param _from the address sending from * @param _to the address sending to */ function batchTransferFrom(uint256[] _tokenIds, address _from, address _to) public { require (isBatchSupported); require (_tokenIds.length > 0 && _from != address(0) && _to != address(0)); uint256 _id; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0); _id = _tokenIds[i]; transferFrom(_from, _to, _id); } } /** * @dev Facilitates batch trasnfer of collectible, depending if batch is supported on contract. * Checks for collectible 0,address 0 and then performs the transfer * @notice Batch SafeTransferFrom with multiple From and to Addresses * @param _tokenIds The asset identifiers * @param _fromB the address sending from * @param _toB the address sending to */ function multiBatchSafeTransferFrom( uint256[] _tokenIds, address[] _fromB, address[] _toB ) public { require (isBatchSupported); require (_tokenIds.length > 0 && _fromB.length > 0 && _toB.length > 0); uint256 _id; address _to; address _from; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0 && _fromB[i] != 0 && _toB[i] != 0); _id = _tokenIds[i]; _to = _toB[i]; _from = _fromB[i]; safeTransferFrom(_from, _to, _id); } } /** * @dev Facilitates batch trasnfer of collectible, depending if batch is supported on contract. * Checks for collectible 0,address 0 and then performs the transfer * @notice Batch SafeTransferFrom from a single address to another address * @param _tokenIds The asset identifiers * @param _from the address sending from * @param _to the address sending to */ function batchSafeTransferFrom( uint256[] _tokenIds, address _from, address _to ) public { require (isBatchSupported); require (_tokenIds.length > 0 && _from != address(0) && _to != address(0)); uint256 _id; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0); _id = _tokenIds[i]; safeTransferFrom(_from, _to, _id); } } /** * @notice Batch Function to approve the spender * @dev Helps to approve a batch of collectibles * @param _tokenIds The asset identifiers * @param _spender The spender */ function batchApprove( uint256[] _tokenIds, address _spender ) public { require (isBatchSupported); require (_tokenIds.length > 0 && _spender != address(0)); uint256 _id; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0); _id = _tokenIds[i]; approve(_spender, _id); } } /** * @dev Batch Function to mark spender for approved for all. Does a check * for address(0) and throws if true * @notice Facilitates batch approveAll * @param _spenders The spenders * @param _approved The approved */ function batchSetApprovalForAll( address[] _spenders, bool _approved ) public { require (isBatchSupported); require (_spenders.length > 0); address _spender; for (uint256 i = 0; i < _spenders.length; ++i) { require (address(_spenders[i]) != address(0)); _spender = _spenders[i]; setApprovalForAll(_spender, _approved); } } /** * @dev Function to request Detachment from our Contract * @notice a wallet can request to detach it collectible, so, that it can be used in other third-party contracts. * @param _tokenId The token identifier */ function requestDetachment( uint256 _tokenId ) public { //Request can only be made by owner or approved address require (isApprovedOrOwner(msg.sender, _tokenId)); uint256 isAttached = checkIsAttached(_tokenId); //If collectible is on a gamecard prevent detachment require(getGameCardId(_tokenId) == 0); require (isAttached >= 1); if(attachedSystemActive == true) { //Checks to see if request was made and if time elapsed if(isAttached > 1 && block.timestamp - isAttached > detachmentTime) { isAttached = 0; } else if(isAttached > 1) { //Forces Tx Fail if time is already set for attachment and not less than detachmentTime require (isAttached == 1); } else { //Is attached, set detachment time and make request to detach // emit AssetUpdated(_tokenId); isAttached = block.timestamp; } } else { isAttached = 0; } updateIsAttached(_tokenId, isAttached); } /** * @dev Function to attach the asset, thus, restricting transfer * @notice Attaches the collectible to our contract * @param _tokenId The token identifier */ function attachAsset( uint256 _tokenId ) public canTransfer(_tokenId) { uint256 isAttached = checkIsAttached(_tokenId); require (isAttached == 0); isAttached = 1; updateIsAttached(_tokenId, isAttached); emit AssetUpdated(_tokenId); } /** * @dev Batch attach function * @param _tokenIds The identifiers */ function batchAttachAssets(uint256[] _tokenIds) public { require (isBatchSupported); for(uint i = 0; i < _tokenIds.length; i++) { attachAsset(_tokenIds[i]); } } /** * @dev Batch detach function * @param _tokenIds The identifiers */ function batchDetachAssets(uint256[] _tokenIds) public { require (isBatchSupported); for(uint i = 0; i < _tokenIds.length; i++) { requestDetachment(_tokenIds[i]); } } /** * @dev Function to facilitate detachment when contract is paused * @param _tokenId The identifiers */ function requestDetachmentOnPause (uint256 _tokenId) public whenPaused { //Request can only be made by owner or approved address require (isApprovedOrOwner(msg.sender, _tokenId)); updateIsAttached(_tokenId, 0); } /** * @dev Toggle the Attachment Switch * @param _state The state */ function toggleAttachedEnforcement (bool _state) public onlyManager { attachedSystemActive = _state; } /** * @dev Set Attachment Time Period (this restricts user from continuously trigger detachment) * @param _time The time */ function setDetachmentTime (uint256 _time) public onlyManager { //Detactment Time can not be set greater than 2 weeks. require (_time <= 1209600); detachmentTime = uint32(_time); } /** * @dev Detach Asset From System * @param _tokenId The token iddentifier */ function setNFTDetached(uint256 _tokenId) public anyOperator { require (checkIsAttached(_tokenId) > 0); updateIsAttached(_tokenId, 0); } /** * @dev Batch function to detach multiple assets * @param _tokenIds The token identifiers */ function setBatchDetachCollectibles(uint256[] _tokenIds) public anyOperator { uint256 _id; for(uint i = 0; i < _tokenIds.length; i++) { _id = _tokenIds[i]; setNFTDetached(_id); } } /** * @dev Function to update attach value * @param _tokenId The asset id * @param _isAttached Indicates if attached */ function updateIsAttached(uint256 _tokenId, uint256 _isAttached) internal { NFT memory obj = _getAttributesOfToken(_tokenId); obj.isAttached = _isAttached; allNFTs[_tokenId] = obj; emit AssetUpdated(_tokenId); } /** * @dev Facilitates Creating Sale using the Sale Contract. Forces owner check & collectibleId check * @notice Helps a wallet to create a sale using our Sale Contract * @param _tokenId The token identifier * @param _startingPrice The starting price * @param _endingPrice The ending price * @param _duration The duration */ function initiateCreateSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external { require (_tokenId != 0); // If DodgersNFT is already on any sale, this will throw // because it will be owned by the sale contract. address owner = ownerOf(_tokenId); require (owner == msg.sender); // Sale contract checks input sizes require (_startingPrice == _startingPrice); require (_endingPrice == _endingPrice); require (_duration == _duration); require (checkIsAttached(_tokenId) == 0); // One time approval for the tokenID _approveForSale(msg.sender, address(saleManagerAddress), _tokenId); saleManagerAddress.createSale(_tokenId, _startingPrice, _endingPrice, _duration, msg.sender); } /** * @dev Facilitates batch auction of collectibles, and enforeces strict checking on the collectibleId,starting/ending price, duration. * @notice Batch function to put 10 or less collectibles on sale * @param _tokenIds The token identifier * @param _startingPrices The starting price * @param _endingPrices The ending price * @param _durations The duration */ function batchCreateAssetSale(uint256[] _tokenIds, uint256[] _startingPrices, uint256[] _endingPrices, uint256[] _durations) external whenNotPaused { require (_tokenIds.length > 0 && _startingPrices.length > 0 && _endingPrices.length > 0 && _durations.length > 0); // Sale contract checks input sizes for(uint ii = 0; ii < _tokenIds.length; ii++){ // Do not process for tokenId 0 require (_tokenIds[ii] != 0); require (_startingPrices[ii] == _startingPrices[ii]); require (_endingPrices[ii] == _endingPrices[ii]); require (_durations[ii] == _durations[ii]); // If DodgersNFT is already on any sale, this will throw // because it will be owned by the sale contract. address _owner = ownerOf(_tokenIds[ii]); address _msgSender = msg.sender; require (_owner == _msgSender); // Check whether the collectible is inPlay. If inPlay cant put it on Sale require (checkIsAttached(_tokenIds[ii]) == 0); // approve token to for Sale creation _approveForSale(msg.sender, address(saleManagerAddress), _tokenIds[ii]); saleManagerAddress.createSale(_tokenIds[ii], _startingPrices[ii], _endingPrices[ii], _durations[ii], msg.sender); } } }
Helper function to get the attirbute of the collectible.To avoid using getCollectibleDetails Returns the ability of an asset/collectible/token from attributes. _tokenId The token identifier return ability ability of the asset/
function getAbilitiesForCollectibleId(uint256 _tokenId) external view returns (uint256 ability) { NFT memory obj = _getAttributesOfToken(_tokenId); uint256 _attributes = uint256(obj.attributes); ability = (_attributes % 1000); }
7,722,496
/** *Submitted for verification at Etherscan.io on 2021-10-29 */ // File openzeppelin-solidity/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File openzeppelin-solidity/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File openzeppelin-solidity/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File openzeppelin-solidity/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File openzeppelin-solidity/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File openzeppelin-solidity/contracts/utils/[email protected] pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File openzeppelin-solidity/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File openzeppelin-solidity/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File openzeppelin-solidity/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract 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}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File openzeppelin-solidity/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File openzeppelin-solidity/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File openzeppelin-solidity/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File openzeppelin-solidity/contracts/utils/math/[email protected] pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File contracts/common/meta-transactions/ContentMixin.sol pragma solidity ^0.8.0; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // File contracts/common/meta-transactions/Initializable.sol pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File contracts/common/meta-transactions/EIP712Base.sol pragma solidity ^0.8.0; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File contracts/common/meta-transactions/NativeMetaTransaction.sol pragma solidity ^0.8.0; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File contracts/assets/ERC721TradableV2.sol pragma solidity ^0.8.0; contract ProxyRegistry { mapping(address => address) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721TradableV2 is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address openseaProxyAddress; address elementProxyAddress; mapping(address => bool) public factoryAddresses; uint256 private _currentTokenId = 0; uint256 public maxSupply = 0; constructor( string memory _name, string memory _symbol, uint256 _maxSupply, address _elementProxyRegistry, address _openseaProxyRegistry ) ERC721(_name, _symbol) { maxSupply = _maxSupply; elementProxyAddress = _elementProxyRegistry; openseaProxyAddress = _openseaProxyRegistry; _initializeEIP712(_name); } function baseTokenURI() virtual public view returns (string memory); function tokenURI(uint256 _tokenId) override public view returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } /** * Override isApprovedForAll to whitelist user's Element proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist Element's proxy contract for easy trading. ProxyRegistry elementProxy = ProxyRegistry(elementProxyAddress); if (address(elementProxy.proxies(owner)) == operator) { return true; } // Whitelist Opensea's proxy contract for easy trading. ProxyRegistry openseaProxy = ProxyRegistry(openseaProxyAddress); if (address(openseaProxy.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by Element. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } /** * add factory addrss */ function addFactoryAddress(address factoryAddr) external onlyOwner { factoryAddresses[factoryAddr] = true; } /** * remove factory addrss */ function removeFactoryAddress(address factoryAddr) external onlyOwner { delete factoryAddresses[factoryAddr]; } /** * add factory addrss */ function setMaxSupply(uint256 _maxSupply) external onlyOwner { require(_maxSupply < maxSupply, "out of max supply"); maxSupply = _maxSupply; } } // File @openzeppelin/contracts/security/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File @openzeppelin/contracts/utils/cryptography/[email protected] pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // 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) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } else if (signature.length == 64) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } } else { revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } /** * @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) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * 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 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)); } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/assets/MaskhumanV2.sol pragma solidity 0.8.9; contract MaskhumanV2 is ERC721TradableV2, ReentrancyGuard { using ECDSA for bytes32; uint256 private maxPresale = 100; uint256 private _presaleNum = 0; uint256 private _presalePrice = 0; //0ETH uint256 private _presaleQty = 1; mapping(address => bool) private _usedAddresses; address private _signerAddress = 0x32f4B63A46c1D12AD82cABC778D75aBF9889821a; //Metasaur Signer uint256 public pricePerToken = 66000000000000000; //0.066ETH uint256 public saleSupply = 1100; uint256 private publicSaleMaxSupply = 1000; uint256 private publicSaleNum = 0; bool public saleLive = true; bool public presaleLive = true; string public baseURI = "https://api.maskhuman.com/v2/token/"; string public contractURI = "https://api.maskhuman.com/v2/contract"; //triggers on mint event event MintInfo(uint256 indexed tokenIdStart, address indexed sender, address indexed to, uint256 qty, uint256 value); constructor(address _elementProxyRegistry, address _opensaeProxyRegistry) ERC721TradableV2("MaskHuman()", "MHN", 10000, _elementProxyRegistry, _opensaeProxyRegistry) {} function baseTokenURI() override public view returns (string memory) { return baseURI; } function setBaseTokenURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } function getContractURI() public view returns (string memory) { return contractURI; } function setContractURI(string memory _contractURI) public onlyOwner { contractURI = _contractURI; } function batchMint(uint256 _qty, address _to) private { uint256 newTokenId = totalSupply() + 1; require(newTokenId <= saleSupply, "out of stock"); for (uint256 i = 0; i < _qty; i++) { _mint(_to, newTokenId + i); } emit MintInfo(newTokenId, _msgSender(), _to, _qty, msg.value); } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(uint256 _qty, address _to) public { require(factoryAddresses[_msgSender()], "not factory"); batchMint(_qty, _to); } // Public buy function publicBuy(uint256 qty) external payable nonReentrant { require(saleLive, "not live "); require(qty <= 20, "no more than 20"); require(pricePerToken * qty == msg.value, "exact amount needed"); require(publicSaleNum + qty <= publicSaleMaxSupply, "public buy out of stock"); publicSaleNum = publicSaleNum + qty; batchMint(qty, _msgSender()); } // Presale buy function presaleBuy(bytes memory sig) external payable nonReentrant { require(presaleLive, "presale not live"); require(matchAddressSigner(msg.sender, sig), "no direct mint"); require(!_usedAddresses[msg.sender], "account already used"); require(_presalePrice * _presaleQty == msg.value, "exact amount needed"); require(_presaleNum + _presaleQty <= maxPresale, "presale out of stock"); _usedAddresses[msg.sender] = true; _presaleNum = _presaleNum + _presaleQty; batchMint(_presaleQty, _msgSender()); } // admin can mint them for giveaways, airdrops etc function adminMint(uint256 qty, address to) public onlyOwner { require(qty > 0, "minimum 1 token"); batchMint(qty, to); } //------------------------------------ //----------- signing code ----------- //------------------------------------ function setSignerAddress(address addr) external onlyOwner { _signerAddress = addr; } function hashSender(address sender) private pure returns (bytes32) { return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(sender))) ); } function matchAddressSigner(address sender, bytes memory signature) private view returns (bool) { // check sender bytes32 hash = hashSender(sender); return _signerAddress == hash.recover(signature); } function checkSignature(address sender, bytes memory signature) external view returns (bool) { // check sender bytes32 hash = hashSender(sender); return _signerAddress == hash.recover(signature) && !_usedAddresses[msg.sender]; } //---------------------------------- //----------- other code ----------- //---------------------------------- function toggleSaleStatus() external onlyOwner { saleLive = !saleLive; } function togglePresaleStatus() external onlyOwner { presaleLive = !presaleLive; } function changePrice(uint256 newPrice) external onlyOwner { pricePerToken = newPrice; } function changeMaxPresale(uint256 newMaxPresale) external onlyOwner { maxPresale = newMaxPresale; } function changeMaxPublicBuy(uint256 newMaxPublicBuy) external onlyOwner { publicSaleMaxSupply = newMaxPublicBuy; } function changePresaleQty(uint256 newQty) external onlyOwner { _presaleQty = newQty; } function changePresalePrice(uint256 newPrice) external onlyOwner { _presalePrice = newPrice; } /** * add factory addrss */ function changeSaleSupply(uint256 _saleSupply) external onlyOwner { require(_saleSupply <= maxSupply, "out of max supply"); saleSupply = _saleSupply; } function withdrawEarnings() public onlyOwner { payable(msg.sender).transfer(address(this).balance); } function reclaimERC20(IERC20 erc20Token) public onlyOwner { erc20Token.transfer(msg.sender, erc20Token.balanceOf(address(this))); } }
add factory addrss/
function addFactoryAddress(address factoryAddr) external onlyOwner { factoryAddresses[factoryAddr] = true; }
2,451,058
// SPDX-License-Identifier: MIT AND GPL-3.0 // File: OpenZeppelin/[email protected]/contracts/access/IAccessControl.sol pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File: OpenZeppelin/[email protected]/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: OpenZeppelin/[email protected]/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: OpenZeppelin/[email protected]/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: OpenZeppelin/[email protected]/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: OpenZeppelin/[email protected]/contracts/access/AccessControl.sol pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/MotionSettings.sol // SPDX-FileCopyrightText: 2021 Lido <[email protected]> pragma solidity ^0.8.4; /// @author psirex /// @notice Provides methods to update motion duration, objections threshold, and limit of active motions of Easy Track contract MotionSettings is AccessControl { // ------------- // EVENTS // ------------- event MotionDurationChanged(uint256 _motionDuration); event MotionsCountLimitChanged(uint256 _newMotionsCountLimit); event ObjectionsThresholdChanged(uint256 _newThreshold); // ------------- // ERRORS // ------------- string private constant ERROR_VALUE_TOO_SMALL = "VALUE_TOO_SMALL"; string private constant ERROR_VALUE_TOO_LARGE = "VALUE_TOO_LARGE"; // ------------ // CONSTANTS // ------------ /// @notice Upper bound for motionsCountLimit variable. uint256 public constant MAX_MOTIONS_LIMIT = 24; /// @notice Upper bound for objectionsThreshold variable. /// @dev Stored in basis points (1% = 100) uint256 public constant MAX_OBJECTIONS_THRESHOLD = 500; /// @notice Lower bound for motionDuration variable uint256 public constant MIN_MOTION_DURATION = 48 hours; /// ------------------ /// STORAGE VARIABLES /// ------------------ /// @notice Percent from total supply of governance tokens required to reject motion. /// @dev Value stored in basis points: 1% == 100. uint256 public objectionsThreshold; /// @notice Max count of active motions uint256 public motionsCountLimit; /// @notice Minimal time required to pass before enacting of motion uint256 public motionDuration; // ------------ // CONSTRUCTOR // ------------ constructor( address _admin, uint256 _motionDuration, uint256 _motionsCountLimit, uint256 _objectionsThreshold ) { _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setMotionDuration(_motionDuration); _setMotionsCountLimit(_motionsCountLimit); _setObjectionsThreshold(_objectionsThreshold); } // ------------------ // EXTERNAL METHODS // ------------------ /// @notice Sets the minimal time required to pass before enacting of motion function setMotionDuration(uint256 _motionDuration) external onlyRole(DEFAULT_ADMIN_ROLE) { _setMotionDuration(_motionDuration); } /// @notice Sets percent from total supply of governance tokens required to reject motion function setObjectionsThreshold(uint256 _objectionsThreshold) external onlyRole(DEFAULT_ADMIN_ROLE) { _setObjectionsThreshold(_objectionsThreshold); } /// @notice Sets max count of active motions. function setMotionsCountLimit(uint256 _motionsCountLimit) external onlyRole(DEFAULT_ADMIN_ROLE) { _setMotionsCountLimit(_motionsCountLimit); } function _setMotionDuration(uint256 _motionDuration) internal { require(_motionDuration >= MIN_MOTION_DURATION, ERROR_VALUE_TOO_SMALL); motionDuration = _motionDuration; emit MotionDurationChanged(_motionDuration); } function _setObjectionsThreshold(uint256 _objectionsThreshold) internal { require(_objectionsThreshold <= MAX_OBJECTIONS_THRESHOLD, ERROR_VALUE_TOO_LARGE); objectionsThreshold = _objectionsThreshold; emit ObjectionsThresholdChanged(_objectionsThreshold); } function _setMotionsCountLimit(uint256 _motionsCountLimit) internal { require(_motionsCountLimit <= MAX_MOTIONS_LIMIT, ERROR_VALUE_TOO_LARGE); motionsCountLimit = _motionsCountLimit; emit MotionsCountLimitChanged(_motionsCountLimit); } } // File: contracts/interfaces/IEVMScriptFactory.sol // SPDX-FileCopyrightText: 2021 Lido <[email protected]> pragma solidity ^0.8.4; /// @author psirex /// @notice Interface which every EVMScript factory used in EasyTrack contract has to implement interface IEVMScriptFactory { function createEVMScript(address _creator, bytes memory _evmScriptCallData) external returns (bytes memory); } // File: contracts/libraries/BytesUtils.sol // SPDX-FileCopyrightText: 2021 Lido <[email protected]> pragma solidity ^0.8.4; /// @author psirex /// @notice Contains methods to extract primitive types from bytes library BytesUtils { function bytes24At(bytes memory data, uint256 location) internal pure returns (bytes24 result) { uint256 word = uint256At(data, location); assembly { result := word } } function addressAt(bytes memory data, uint256 location) internal pure returns (address result) { uint256 word = uint256At(data, location); assembly { result := shr( 96, and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000) ) } } function uint32At(bytes memory _data, uint256 _location) internal pure returns (uint32 result) { uint256 word = uint256At(_data, _location); assembly { result := shr( 224, and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000) ) } } function uint256At(bytes memory data, uint256 location) internal pure returns (uint256 result) { assembly { result := mload(add(data, add(0x20, location))) } } } // File: contracts/libraries/EVMScriptPermissions.sol // SPDX-FileCopyrightText: 2021 Lido <[email protected]> pragma solidity ^0.8.4; /// @author psirex /// @notice Provides methods to convinient work with permissions bytes /// @dev Permissions - is a list of tuples (address, bytes4) encoded into a bytes representation. /// Each tuple (address, bytes4) describes a method allowed to be called by EVMScript library EVMScriptPermissions { using BytesUtils for bytes; // ------------- // CONSTANTS // ------------- /// Bytes size of SPEC_ID in EVMScript uint256 private constant SPEC_ID_SIZE = 4; /// Size of the address type in bytes uint256 private constant ADDRESS_SIZE = 20; /// Bytes size of calldata length in EVMScript uint256 private constant CALLDATA_LENGTH_SIZE = 4; /// Bytes size of method selector uint256 private constant METHOD_SELECTOR_SIZE = 4; /// Bytes size of one item in permissions uint256 private constant PERMISSION_SIZE = ADDRESS_SIZE + METHOD_SELECTOR_SIZE; // ------------------ // INTERNAL METHODS // ------------------ /// @notice Validates that passed EVMScript calls only methods allowed in permissions. /// @dev Returns false if provided permissions are invalid (has a wrong length or empty) function canExecuteEVMScript(bytes memory _permissions, bytes memory _evmScript) internal pure returns (bool) { uint256 location = SPEC_ID_SIZE; // first 4 bytes reserved for SPEC_ID if (!isValidPermissions(_permissions) || _evmScript.length <= location) { return false; } while (location < _evmScript.length) { (bytes24 methodToCall, uint32 callDataLength) = _getNextMethodId(_evmScript, location); if (!_hasPermission(_permissions, methodToCall)) { return false; } location += ADDRESS_SIZE + CALLDATA_LENGTH_SIZE + callDataLength; } return true; } /// @notice Validates that bytes with permissions not empty and has correct length function isValidPermissions(bytes memory _permissions) internal pure returns (bool) { return _permissions.length > 0 && _permissions.length % PERMISSION_SIZE == 0; } // Retrieves bytes24 which describes tuple (address, bytes4) // from EVMScript starting from _location position function _getNextMethodId(bytes memory _evmScript, uint256 _location) private pure returns (bytes24, uint32) { address recipient = _evmScript.addressAt(_location); uint32 callDataLength = _evmScript.uint32At(_location + ADDRESS_SIZE); uint32 functionSelector = _evmScript.uint32At(_location + ADDRESS_SIZE + CALLDATA_LENGTH_SIZE); return (bytes24(uint192(functionSelector)) | bytes20(recipient), callDataLength); } // Validates that passed _methodToCall contained in permissions function _hasPermission(bytes memory _permissions, bytes24 _methodToCall) private pure returns (bool) { uint256 location = 0; while (location < _permissions.length) { bytes24 permission = _permissions.bytes24At(location); if (permission == _methodToCall) { return true; } location += PERMISSION_SIZE; } return false; } } // File: contracts/EVMScriptFactoriesRegistry.sol // SPDX-FileCopyrightText: 2021 Lido <[email protected]> pragma solidity ^0.8.4; /// @author psirex /// @notice Provides methods to add/remove EVMScript factories /// and contains an internal method for the convenient creation of EVMScripts contract EVMScriptFactoriesRegistry is AccessControl { using EVMScriptPermissions for bytes; // ------------- // EVENTS // ------------- event EVMScriptFactoryAdded(address indexed _evmScriptFactory, bytes _permissions); event EVMScriptFactoryRemoved(address indexed _evmScriptFactory); // ------------ // STORAGE VARIABLES // ------------ /// @notice List of allowed EVMScript factories address[] public evmScriptFactories; // Position of the EVMScript factory in the `evmScriptFactories` array, // plus 1 because index 0 means a value is not in the set. mapping(address => uint256) internal evmScriptFactoryIndices; /// @notice Permissions of current list of allowed EVMScript factories. mapping(address => bytes) public evmScriptFactoryPermissions; // ------------ // CONSTRUCTOR // ------------ constructor(address _admin) { _setupRole(DEFAULT_ADMIN_ROLE, _admin); } // ------------------ // EXTERNAL METHODS // ------------------ /// @notice Adds new EVMScript Factory to the list of allowed EVMScript factories with given permissions. /// Be careful about factories and their permissions added via this method. Only reviewed and tested /// factories must be added via this method. function addEVMScriptFactory(address _evmScriptFactory, bytes memory _permissions) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_permissions.isValidPermissions(), "INVALID_PERMISSIONS"); require(!_isEVMScriptFactory(_evmScriptFactory), "EVM_SCRIPT_FACTORY_ALREADY_ADDED"); evmScriptFactories.push(_evmScriptFactory); evmScriptFactoryIndices[_evmScriptFactory] = evmScriptFactories.length; evmScriptFactoryPermissions[_evmScriptFactory] = _permissions; emit EVMScriptFactoryAdded(_evmScriptFactory, _permissions); } /// @notice Removes EVMScript factory from the list of allowed EVMScript factories /// @dev To delete a EVMScript factory from the rewardPrograms 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'). function removeEVMScriptFactory(address _evmScriptFactory) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 index = _getEVMScriptFactoryIndex(_evmScriptFactory); uint256 lastIndex = evmScriptFactories.length - 1; if (index != lastIndex) { address lastEVMScriptFactory = evmScriptFactories[lastIndex]; evmScriptFactories[index] = lastEVMScriptFactory; evmScriptFactoryIndices[lastEVMScriptFactory] = index + 1; } evmScriptFactories.pop(); delete evmScriptFactoryIndices[_evmScriptFactory]; delete evmScriptFactoryPermissions[_evmScriptFactory]; emit EVMScriptFactoryRemoved(_evmScriptFactory); } /// @notice Returns current list of EVMScript factories function getEVMScriptFactories() external view returns (address[] memory) { return evmScriptFactories; } /// @notice Returns if passed address are listed as EVMScript factory in the registry function isEVMScriptFactory(address _maybeEVMScriptFactory) external view returns (bool) { return _isEVMScriptFactory(_maybeEVMScriptFactory); } // ------------------ // INTERNAL METHODS // ------------------ /// @notice Creates EVMScript using given EVMScript factory /// @dev Checks permissions of resulting EVMScript and reverts with error /// if script tries to call methods not listed in permissions function _createEVMScript( address _evmScriptFactory, address _creator, bytes memory _evmScriptCallData ) internal returns (bytes memory _evmScript) { require(_isEVMScriptFactory(_evmScriptFactory), "EVM_SCRIPT_FACTORY_NOT_FOUND"); _evmScript = IEVMScriptFactory(_evmScriptFactory).createEVMScript( _creator, _evmScriptCallData ); bytes memory permissions = evmScriptFactoryPermissions[_evmScriptFactory]; require(permissions.canExecuteEVMScript(_evmScript), "HAS_NO_PERMISSIONS"); } // ------------------ // PRIVATE METHODS // ------------------ function _getEVMScriptFactoryIndex(address _evmScriptFactory) private view returns (uint256 _index) { _index = evmScriptFactoryIndices[_evmScriptFactory]; require(_index > 0, "EVM_SCRIPT_FACTORY_NOT_FOUND"); _index -= 1; } function _isEVMScriptFactory(address _maybeEVMScriptFactory) private view returns (bool) { return evmScriptFactoryIndices[_maybeEVMScriptFactory] > 0; } } // File: contracts/interfaces/IEVMScriptExecutor.sol // SPDX-FileCopyrightText: 2021 Lido <[email protected]> pragma solidity ^0.8.4; /// @notice Interface of EVMScript executor used by EasyTrack interface IEVMScriptExecutor { function executeEVMScript(bytes memory _evmScript) external returns (bytes memory); } // File: OpenZeppelin/[email protected]/contracts/security/Pausable.sol pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: contracts/EasyTrack.sol // SPDX-FileCopyrightText: 2021 Lido <[email protected]> pragma solidity ^0.8.4; interface IMiniMeToken { function balanceOfAt(address _owner, uint256 _blockNumber) external pure returns (uint256); function totalSupplyAt(uint256 _blockNumber) external view returns (uint256); } /// @author psirex /// @notice Contains main logic of Easy Track contract EasyTrack is Pausable, AccessControl, MotionSettings, EVMScriptFactoriesRegistry { struct Motion { uint256 id; address evmScriptFactory; address creator; uint256 duration; uint256 startDate; uint256 snapshotBlock; uint256 objectionsThreshold; uint256 objectionsAmount; bytes32 evmScriptHash; } // ------------- // EVENTS // ------------- event MotionCreated( uint256 indexed _motionId, address _creator, address indexed _evmScriptFactory, bytes _evmScriptCallData, bytes _evmScript ); event MotionObjected( uint256 indexed _motionId, address indexed _objector, uint256 _weight, uint256 _newObjectionsAmount, uint256 _newObjectionsAmountPct ); event MotionRejected(uint256 indexed _motionId); event MotionCanceled(uint256 indexed _motionId); event MotionEnacted(uint256 indexed _motionId); event EVMScriptExecutorChanged(address indexed _evmScriptExecutor); // ------------- // ERRORS // ------------- string private constant ERROR_ALREADY_OBJECTED = "ALREADY_OBJECTED"; string private constant ERROR_NOT_ENOUGH_BALANCE = "NOT_ENOUGH_BALANCE"; string private constant ERROR_NOT_CREATOR = "NOT_CREATOR"; string private constant ERROR_MOTION_NOT_PASSED = "MOTION_NOT_PASSED"; string private constant ERROR_UNEXPECTED_EVM_SCRIPT = "UNEXPECTED_EVM_SCRIPT"; string private constant ERROR_MOTION_NOT_FOUND = "MOTION_NOT_FOUND"; string private constant ERROR_MOTIONS_LIMIT_REACHED = "MOTIONS_LIMIT_REACHED"; // ------------- // ROLES // ------------- bytes32 public constant PAUSE_ROLE = keccak256("PAUSE_ROLE"); bytes32 public constant UNPAUSE_ROLE = keccak256("UNPAUSE_ROLE"); bytes32 public constant CANCEL_ROLE = keccak256("CANCEL_ROLE"); // ------------- // CONSTANTS // ------------- // Stores 100% in basis points uint256 internal constant HUNDRED_PERCENT = 10000; // ------------ // STORAGE VARIABLES // ------------ /// @notice List of active motions Motion[] public motions; // Id of the lastly created motion uint256 internal lastMotionId; /// @notice Address of governanceToken which implements IMiniMeToken interface IMiniMeToken public governanceToken; /// @notice Address of current EVMScriptExecutor IEVMScriptExecutor public evmScriptExecutor; // Position of the motion in the `motions` array, plus 1 // because index 0 means a value is not in the set. mapping(uint256 => uint256) internal motionIndicesByMotionId; /// @notice Stores if motion with given id has been objected from given address. mapping(uint256 => mapping(address => bool)) public objections; // ------------ // CONSTRUCTOR // ------------ constructor( address _governanceToken, address _admin, uint256 _motionDuration, uint256 _motionsCountLimit, uint256 _objectionsThreshold ) EVMScriptFactoriesRegistry(_admin) MotionSettings(_admin, _motionDuration, _motionsCountLimit, _objectionsThreshold) { _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(PAUSE_ROLE, _admin); _setupRole(UNPAUSE_ROLE, _admin); _setupRole(CANCEL_ROLE, _admin); governanceToken = IMiniMeToken(_governanceToken); } // ------------------ // EXTERNAL METHODS // ------------------ /// @notice Creates new motion /// @param _evmScriptFactory Address of EVMScript factory registered in Easy Track /// @param _evmScriptCallData Encoded call data of EVMScript factory /// @return _newMotionId Id of created motion function createMotion(address _evmScriptFactory, bytes memory _evmScriptCallData) external whenNotPaused returns (uint256 _newMotionId) { require(motions.length < motionsCountLimit, ERROR_MOTIONS_LIMIT_REACHED); Motion storage newMotion = motions.push(); _newMotionId = ++lastMotionId; newMotion.id = _newMotionId; newMotion.creator = msg.sender; newMotion.startDate = block.timestamp; newMotion.snapshotBlock = block.number; newMotion.duration = motionDuration; newMotion.objectionsThreshold = objectionsThreshold; newMotion.evmScriptFactory = _evmScriptFactory; motionIndicesByMotionId[_newMotionId] = motions.length; bytes memory evmScript = _createEVMScript(_evmScriptFactory, msg.sender, _evmScriptCallData); newMotion.evmScriptHash = keccak256(evmScript); emit MotionCreated( _newMotionId, msg.sender, _evmScriptFactory, _evmScriptCallData, evmScript ); } /// @notice Enacts motion with given id /// @param _motionId Id of motion to enact /// @param _evmScriptCallData Encoded call data of EVMScript factory. Same as passed on the creation /// of motion with the given motion id. Transaction reverts if EVMScript factory call data differs function enactMotion(uint256 _motionId, bytes memory _evmScriptCallData) external whenNotPaused { Motion storage motion = _getMotion(_motionId); require(motion.startDate + motion.duration <= block.timestamp, ERROR_MOTION_NOT_PASSED); address creator = motion.creator; bytes32 evmScriptHash = motion.evmScriptHash; address evmScriptFactory = motion.evmScriptFactory; _deleteMotion(_motionId); emit MotionEnacted(_motionId); bytes memory evmScript = _createEVMScript(evmScriptFactory, creator, _evmScriptCallData); require(evmScriptHash == keccak256(evmScript), ERROR_UNEXPECTED_EVM_SCRIPT); evmScriptExecutor.executeEVMScript(evmScript); } /// @notice Submits an objection from `governanceToken` holder. /// @param _motionId Id of motion to object function objectToMotion(uint256 _motionId) external { Motion storage motion = _getMotion(_motionId); require(!objections[_motionId][msg.sender], ERROR_ALREADY_OBJECTED); objections[_motionId][msg.sender] = true; uint256 snapshotBlock = motion.snapshotBlock; uint256 objectorBalance = governanceToken.balanceOfAt(msg.sender, snapshotBlock); require(objectorBalance > 0, ERROR_NOT_ENOUGH_BALANCE); uint256 totalSupply = governanceToken.totalSupplyAt(snapshotBlock); uint256 newObjectionsAmount = motion.objectionsAmount + objectorBalance; uint256 newObjectionsAmountPct = (HUNDRED_PERCENT * newObjectionsAmount) / totalSupply; emit MotionObjected( _motionId, msg.sender, objectorBalance, newObjectionsAmount, newObjectionsAmountPct ); if (newObjectionsAmountPct < motion.objectionsThreshold) { motion.objectionsAmount = newObjectionsAmount; } else { _deleteMotion(_motionId); emit MotionRejected(_motionId); } } /// @notice Cancels motion with given id /// @param _motionId Id of motion to cancel /// @dev Method reverts if it is called with not existed _motionId function cancelMotion(uint256 _motionId) external { Motion storage motion = _getMotion(_motionId); require(motion.creator == msg.sender, ERROR_NOT_CREATOR); _deleteMotion(_motionId); emit MotionCanceled(_motionId); } /// @notice Cancels all motions with given ids /// @param _motionIds Ids of motions to cancel function cancelMotions(uint256[] memory _motionIds) external onlyRole(CANCEL_ROLE) { for (uint256 i = 0; i < _motionIds.length; ++i) { if (motionIndicesByMotionId[_motionIds[i]] > 0) { _deleteMotion(_motionIds[i]); emit MotionCanceled(_motionIds[i]); } } } /// @notice Cancels all active motions function cancelAllMotions() external onlyRole(CANCEL_ROLE) { uint256 motionsCount = motions.length; while (motionsCount > 0) { motionsCount -= 1; uint256 motionId = motions[motionsCount].id; _deleteMotion(motionId); emit MotionCanceled(motionId); } } /// @notice Sets new EVMScriptExecutor /// @param _evmScriptExecutor Address of new EVMScriptExecutor function setEVMScriptExecutor(address _evmScriptExecutor) external onlyRole(DEFAULT_ADMIN_ROLE) { evmScriptExecutor = IEVMScriptExecutor(_evmScriptExecutor); emit EVMScriptExecutorChanged(_evmScriptExecutor); } /// @notice Pauses Easy Track if it isn't paused. /// Paused Easy Track can't create and enact motions function pause() external whenNotPaused onlyRole(PAUSE_ROLE) { _pause(); } /// @notice Unpauses Easy Track if it is paused function unpause() external whenPaused onlyRole(UNPAUSE_ROLE) { _unpause(); } /// @notice Returns if an _objector can submit an objection to motion with id equals to _motionId or not /// @param _motionId Id of motion to check opportunity to object /// @param _objector Address of objector function canObjectToMotion(uint256 _motionId, address _objector) external view returns (bool) { Motion storage motion = _getMotion(_motionId); uint256 balance = governanceToken.balanceOfAt(_objector, motion.snapshotBlock); return balance > 0 && !objections[_motionId][_objector]; } /// @notice Returns list of active motions function getMotions() external view returns (Motion[] memory) { return motions; } /// @notice Returns motion with the given id /// @param _motionId Id of motion to retrieve function getMotion(uint256 _motionId) external view returns (Motion memory) { return _getMotion(_motionId); } // ------- // PRIVATE METHODS // ------- // Removes motion from list of active moitons // To delete a motion from the moitons 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'). function _deleteMotion(uint256 _motionId) private { uint256 index = motionIndicesByMotionId[_motionId] - 1; uint256 lastIndex = motions.length - 1; if (index != lastIndex) { Motion storage lastMotion = motions[lastIndex]; motions[index] = lastMotion; motionIndicesByMotionId[lastMotion.id] = index + 1; } motions.pop(); delete motionIndicesByMotionId[_motionId]; } // Returns motion with given id if it exists function _getMotion(uint256 _motionId) private view returns (Motion storage) { uint256 _motionIndex = motionIndicesByMotionId[_motionId]; require(_motionIndex > 0, ERROR_MOTION_NOT_FOUND); return motions[_motionIndex - 1]; } }
Returns motion with given id if it exists
function _getMotion(uint256 _motionId) private view returns (Motion storage) { uint256 _motionIndex = motionIndicesByMotionId[_motionId]; require(_motionIndex > 0, ERROR_MOTION_NOT_FOUND); return motions[_motionIndex - 1]; }
1,144,492
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/lib/ConsiderationErrors.sol
Reverts execution with an "UnresolvedOfferCriteria" error message./
) pure { function _revertUnresolvedOfferCriteria( uint256 orderIndex, uint256 offerIndex assembly { mstore(0, UnresolvedOfferCriteria_error_selector) mstore(UnresolvedOfferCriteria_error_orderIndex_ptr, orderIndex) mstore(UnresolvedOfferCriteria_error_offerIndex_ptr, offerIndex) revert(Error_selector_offset, UnresolvedOfferCriteria_error_length) } }
4,301,469
./full_match/1/0x5E57C528EF9126200D76620e7b843600635E74Ca/sources/sir-token.sol
returns data of Total struct
function getTotals() external view returns(Totals memory) { return Total; }
17,066,148
./full_match/97/0xF7FCC686158A97f82DE82437d4553E3Da017157d/sources/project_/contracts/core/erc721_upgradeable/LivNFTUpgradeable.sol
An exterval method that allow CLevel to set readyToBreedPeriod _readyToBreedPeriod - New Ready to breed period
function setReadyToBreedPeriod(uint256 _readyToBreedPeriod) external onlyCLevel{ readyToBreedPeriod = _readyToBreedPeriod; }
3,263,687
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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' // 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) + 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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library 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: GPL-2.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./ModuleMapConsumer.sol"; import "../interfaces/IKernel.sol"; abstract contract Controlled is Initializable, ModuleMapConsumer { // controller address => is a controller mapping(address => bool) internal _controllers; address[] public controllers; function __Controlled_init(address[] memory controllers_, address moduleMap_) public initializer { for (uint256 i; i < controllers_.length; i++) { _controllers[controllers_[i]] = true; } controllers = controllers_; __ModuleMapConsumer_init(moduleMap_); } function addController(address controller) external onlyOwner { _controllers[controller] = true; bool added; for (uint256 i; i < controllers.length; i++) { if (controller == controllers[i]) { added = true; } } if (!added) { controllers.push(controller); } } modifier onlyOwner() { require( IKernel(moduleMap.getModuleAddress(Modules.Kernel)).isOwner(msg.sender), "Controlled::onlyOwner: Caller is not owner" ); _; } modifier onlyManager() { require( IKernel(moduleMap.getModuleAddress(Modules.Kernel)).isManager(msg.sender), "Controlled::onlyManager: Caller is not manager" ); _; } modifier onlyController() { require( _controllers[msg.sender], "Controlled::onlyController: Caller is not controller" ); _; } } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../interfaces/IModuleMap.sol"; abstract contract ModuleMapConsumer is Initializable { IModuleMap public moduleMap; function __ModuleMapConsumer_init(address moduleMap_) internal initializer { moduleMap = IModuleMap(moduleMap_); } } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "./Controlled.sol"; import "./ModuleMapConsumer.sol"; import "../interfaces/ISushiSwapTrader.sol"; import "../interfaces/ISushiSwapFactory.sol"; import "../interfaces/ISushiSwapRouter.sol"; import "../interfaces/ISushiSwapPair.sol"; import "../interfaces/IIntegrationMap.sol"; /// @notice Integrates 0x Nodes to SushiSwap contract SushiSwapTrader is Initializable, ModuleMapConsumer, Controlled, ISushiSwapTrader { using SafeERC20Upgradeable for IERC20MetadataUpgradeable; uint24 private constant SLIPPAGE_DENOMINATOR = 1_000_000; uint24 private slippageNumerator; address private factoryAddress; address private swapRouterAddress; event ExecutedSwapExactInput( address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOutMin, uint256 amountOut ); event FailedSwapExactInput( address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOutMin ); event SushiSwapSlippageNumeratorUpdated(uint24 slippageNumerator); /// @param controllers_ The addresses of the controlling contracts /// @param moduleMap_ The address of the module map contract /// @param factoryAddress_ The address of the SushiSwap factory contract /// @param swapRouterAddress_ The address of the SushiSwap swap router contract /// @param slippageNumerator_ The number divided by the slippage denominator to get the slippage percentage function initialize( address[] memory controllers_, address moduleMap_, address factoryAddress_, address swapRouterAddress_, uint24 slippageNumerator_ ) public initializer { require( slippageNumerator <= SLIPPAGE_DENOMINATOR, "SushiSwapTrader::initialize: Slippage Numerator must be less than or equal to slippage denominator" ); __Controlled_init(controllers_, moduleMap_); __ModuleMapConsumer_init(moduleMap_); factoryAddress = factoryAddress_; swapRouterAddress = swapRouterAddress_; slippageNumerator = slippageNumerator_; } /// @param slippageNumerator_ The number divided by the slippage denominator to get the slippage percentage function updateSlippageNumerator(uint24 slippageNumerator_) external override onlyManager { require( slippageNumerator_ != slippageNumerator, "SushiSwapTrader::setSlippageNumerator: Slippage numerator must be set to a new value" ); require( slippageNumerator <= SLIPPAGE_DENOMINATOR, "SushiSwapTrader::setSlippageNumerator: Slippage Numerator must be less than or equal to slippage denominator" ); slippageNumerator = slippageNumerator_; emit SushiSwapSlippageNumeratorUpdated(slippageNumerator_); } /// @notice Swaps all WETH held in this contract for BIOS and sends to the kernel /// @return Bool indicating whether the trade succeeded function biosBuyBack() external override onlyController returns (bool) { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); address wethAddress = integrationMap.getWethTokenAddress(); address biosAddress = integrationMap.getBiosTokenAddress(); uint256 wethAmountIn = IERC20MetadataUpgradeable(wethAddress).balanceOf( address(this) ); uint256 biosAmountOutMin = getAmountOutMinimum( wethAddress, biosAddress, wethAmountIn ); return swapExactInput( wethAddress, integrationMap.getBiosTokenAddress(), moduleMap.getModuleAddress(Modules.Kernel), wethAmountIn, biosAmountOutMin ); } /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param recipient The address of the token out recipient /// @param amountIn The exact amount of the input to swap /// @param amountOutMin The minimum amount of tokenOut to receive from the swap /// @return bool Indicates whether the swap succeeded function swapExactInput( address tokenIn, address tokenOut, address recipient, uint256 amountIn, uint256 amountOutMin ) public override onlyController returns (bool) { require( IERC20MetadataUpgradeable(tokenIn).balanceOf(address(this)) >= amountIn, "SushiSwapTrader::swapExactInput: Balance is less than trade amount" ); address[] memory path = new address[](2); path[0] = tokenIn; path[1] = tokenOut; uint256 deadline = block.timestamp; if ( IERC20MetadataUpgradeable(tokenIn).allowance( address(this), swapRouterAddress ) == 0 ) { IERC20MetadataUpgradeable(tokenIn).safeApprove( swapRouterAddress, type(uint256).max ); } uint256 tokenOutBalanceBefore = IERC20MetadataUpgradeable(tokenOut) .balanceOf(recipient); try ISushiSwapRouter(swapRouterAddress).swapExactTokensForTokens( amountIn, amountOutMin, path, recipient, deadline ) { emit ExecutedSwapExactInput( tokenIn, tokenOut, amountIn, amountOutMin, IERC20MetadataUpgradeable(tokenOut).balanceOf(recipient) - tokenOutBalanceBefore ); return true; } catch { emit FailedSwapExactInput(tokenIn, tokenOut, amountIn, amountOutMin); return false; } } /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param amountIn The exact amount of the input to swap /// @return amountOutMinimum The minimum amount of tokenOut to receive, factoring in allowable slippage function getAmountOutMinimum( address tokenIn, address tokenOut, uint256 amountIn ) public view returns (uint256 amountOutMinimum) { amountOutMinimum = (getAmountOut(tokenIn, tokenOut, amountIn) * (SLIPPAGE_DENOMINATOR - slippageNumerator)) / SLIPPAGE_DENOMINATOR; } /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param amountIn The exact amount of the input to swap /// @return amountOut The estimated amount of tokenOut to receive function getAmountOut( address tokenIn, address tokenOut, uint256 amountIn ) public view returns (uint256 amountOut) { require( amountIn > 0, "SushiSwapTrader::getAmountOut: amountIn must be greater than zero" ); (uint256 reserveIn, uint256 reserveOut) = getReserves(tokenIn, tokenOut); require( reserveIn > 0 && reserveOut > 0, "SushiSwapTrader::getAmountOut: No liquidity in pool reserves" ); uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * (reserveOut); uint256 denominator = reserveIn * 1000 + amountInWithFee; amountOut = numerator / denominator; } /// @param tokenA The address of tokenA /// @param tokenB The address of tokenB /// @return reserveA The reserve balance of tokenA in the pool /// @return reserveB The reserve balance of tokenB in the pool function getReserves(address tokenA, address tokenB) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = getTokensSorted(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = ISushiSwapPair( getPairFor(tokenA, tokenB) ).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } /// @param tokenA The address of tokenA /// @param tokenB The address of tokenB /// @return token0 The address of sorted token0 /// @return token1 The address of sorted token1 function getTokensSorted(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require( tokenA != tokenB, "SushiSwapTrader::sortToken: Identical token addresses" ); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "SushiSwapTrader::sortToken: Zero address"); } /// @param tokenA The address of tokenA /// @param tokenB The address of tokenB /// @return pair The address of the SushiSwap pool contract function getPairFor(address tokenA, address tokenB) internal view returns (address pair) { pair = ISushiSwapFactory(factoryAddress).getPair(tokenA, tokenB); } /// @return SushiSwap Factory address function getFactoryAddress() public view returns (address) { return factoryAddress; } /// @return The slippage numerator function getSlippageNumerator() public view returns (uint24) { return slippageNumerator; } /// @return The slippage denominator function getSlippageDenominator() public pure returns (uint24) { return SLIPPAGE_DENOMINATOR; } } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IIntegrationMap { struct Integration { bool added; string name; } struct Token { uint256 id; bool added; bool acceptingDeposits; bool acceptingWithdrawals; uint256 biosRewardWeight; uint256 reserveRatioNumerator; } /// @param contractAddress The address of the integration contract /// @param name The name of the protocol being integrated to function addIntegration(address contractAddress, string memory name) external; /// @param tokenAddress The address of the ERC20 token contract /// @param acceptingDeposits Whether token deposits are enabled /// @param acceptingWithdrawals Whether token withdrawals are enabled /// @param biosRewardWeight Token weight for BIOS rewards /// @param reserveRatioNumerator Number that gets divided by reserve ratio denominator to get reserve ratio function addToken( address tokenAddress, bool acceptingDeposits, bool acceptingWithdrawals, uint256 biosRewardWeight, uint256 reserveRatioNumerator ) external; /// @param tokenAddress The address of the token ERC20 contract function enableTokenDeposits(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract function disableTokenDeposits(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract function enableTokenWithdrawals(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract function disableTokenWithdrawals(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract /// @param rewardWeight The updated token BIOS reward weight function updateTokenRewardWeight(address tokenAddress, uint256 rewardWeight) external; /// @param tokenAddress the address of the token ERC20 contract /// @param reserveRatioNumerator Number that gets divided by reserve ratio denominator to get reserve ratio function updateTokenReserveRatioNumerator( address tokenAddress, uint256 reserveRatioNumerator ) external; /// @param integrationId The ID of the integration /// @return The address of the integration contract function getIntegrationAddress(uint256 integrationId) external view returns (address); /// @param integrationAddress The address of the integration contract /// @return The name of the of the protocol being integrated to function getIntegrationName(address integrationAddress) external view returns (string memory); /// @return The address of the WETH token function getWethTokenAddress() external view returns (address); /// @return The address of the BIOS token function getBiosTokenAddress() external view returns (address); /// @param tokenId The ID of the token /// @return The address of the token ERC20 contract function getTokenAddress(uint256 tokenId) external view returns (address); /// @param tokenAddress The address of the token ERC20 contract /// @return The index of the token in the tokens array function getTokenId(address tokenAddress) external view returns (uint256); /// @param tokenAddress The address of the token ERC20 contract /// @return The token BIOS reward weight function getTokenBiosRewardWeight(address tokenAddress) external view returns (uint256); /// @return rewardWeightSum reward weight of depositable tokens function getBiosRewardWeightSum() external view returns (uint256 rewardWeightSum); /// @param tokenAddress The address of the token ERC20 contract /// @return bool indicating whether depositing this token is currently enabled function getTokenAcceptingDeposits(address tokenAddress) external view returns (bool); /// @param tokenAddress The address of the token ERC20 contract /// @return bool indicating whether withdrawing this token is currently enabled function getTokenAcceptingWithdrawals(address tokenAddress) external view returns (bool); // @param tokenAddress The address of the token ERC20 contract // @return bool indicating whether the token has been added function getIsTokenAdded(address tokenAddress) external view returns (bool); // @param integrationAddress The address of the integration contract // @return bool indicating whether the integration has been added function getIsIntegrationAdded(address tokenAddress) external view returns (bool); /// @notice get the length of supported tokens /// @return The quantity of tokens added function getTokenAddressesLength() external view returns (uint256); /// @notice get the length of supported integrations /// @return The quantity of integrations added function getIntegrationAddressesLength() external view returns (uint256); /// @param tokenAddress The address of the token ERC20 contract /// @return The value that gets divided by the reserve ratio denominator function getTokenReserveRatioNumerator(address tokenAddress) external view returns (uint256); /// @return The token reserve ratio denominator function getReserveRatioDenominator() external view returns (uint32); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IKernel { /// @param account The address of the account to check if they are a manager /// @return Bool indicating whether the account is a manger function isManager(address account) external view returns (bool); /// @param account The address of the account to check if they are an owner /// @return Bool indicating whether the account is an owner function isOwner(address account) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; enum Modules { Kernel, // 0 UserPositions, // 1 YieldManager, // 2 IntegrationMap, // 3 BiosRewards, // 4 EtherRewards, // 5 SushiSwapTrader, // 6 UniswapTrader, // 7 StrategyMap, // 8 StrategyManager // 9 } interface IModuleMap { function getModuleAddress(Modules key) external view returns (address); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface ISushiSwapFactory { function getPair(address tokenA, address tokenB) external view returns (address pair); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface ISushiSwapPair { function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function token0() external view returns (address); function token1() external view returns (address); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface ISushiSwapRouter { 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 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 removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function swapETHForExactTokens( uint amountOut, address[] calldata path, address to, uint deadline ) external payable returns (uint[] memory amounts); function swapExactETHForTokens( uint amountOut, address[] calldata path, address to, uint deadline ) external payable returns (uint[] memory amounts); function WETH() external pure returns (address); 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); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface ISushiSwapTrader { /// @param slippageNumerator_ The number divided by the slippage denominator to get the slippage percentage function updateSlippageNumerator(uint24 slippageNumerator_) external; /// @notice Swaps all WETH held in this contract for BIOS and sends to the kernel /// @return Bool indicating whether the trade succeeded function biosBuyBack() external returns (bool); /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param recipient The address of the token out recipient /// @param amountIn The exact amount of the input to swap /// @param amountOutMin The minimum amount of tokenOut to receive from the swap /// @return bool Indicates whether the swap succeeded function swapExactInput( address tokenIn, address tokenOut, address recipient, uint256 amountIn, uint256 amountOutMin ) external returns (bool); }
return The slippage numerator
function getSlippageNumerator() public view returns (uint24) { return slippageNumerator; }
9,947,467
pragma solidity ^0.4.13; interface FundInterface { // EVENTS event PortfolioContent(address[] assets, uint[] holdings, uint[] prices); event RequestUpdated(uint id); event Redeemed(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); event FeesConverted(uint atTimestamp, uint shareQuantityConverted, uint unclaimed); event CalculationUpdate(uint atTimestamp, uint managementFee, uint performanceFee, uint nav, uint sharePrice, uint totalSupply); event ErrorMessage(string errorMessage); // EXTERNAL METHODS // Compliance by Investor function requestInvestment(uint giveQuantity, uint shareQuantity, address investmentAsset) external; function executeRequest(uint requestId) external; function cancelRequest(uint requestId) external; function redeemAllOwnedAssets(uint shareQuantity) external returns (bool); // Administration by Manager function enableInvestment(address[] ofAssets) external; function disableInvestment(address[] ofAssets) external; function shutDown() external; // PUBLIC METHODS function emergencyRedeem(uint shareQuantity, address[] requestedAssets) public returns (bool success); function calcSharePriceAndAllocateFees() public returns (uint); // PUBLIC VIEW METHODS // Get general information function getModules() view returns (address, address, address); function getLastRequestId() view returns (uint); function getManager() view returns (address); // Get accounting information function performCalculations() view returns (uint, uint, uint, uint, uint, uint, uint); function calcSharePrice() view returns (uint); } interface AssetInterface { /* * Implements ERC 20 standard. * https://github.com/ethereum/EIPs/blob/f90864a3d2b2b45c4decf95efd26b3f0c276051a/EIPS/eip-20-token-standard.md * https://github.com/ethereum/EIPs/issues/20 * * Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload. * https://github.com/ethereum/EIPs/issues/223 */ // Events event Approval(address indexed _owner, address indexed _spender, uint _value); // There is no ERC223 compatible Transfer event, with `_data` included. //ERC 223 // PUBLIC METHODS function transfer(address _to, uint _value, bytes _data) public returns (bool success); // ERC 20 // PUBLIC METHODS function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); // PUBLIC VIEW METHODS function balanceOf(address _owner) view public returns (uint balance); function allowance(address _owner, address _spender) public view returns (uint remaining); } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } interface SharesInterface { event Created(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); event Annihilated(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); // VIEW METHODS function getName() view returns (bytes32); function getSymbol() view returns (bytes8); function getDecimals() view returns (uint); function getCreationTime() view returns (uint); function toSmallestShareUnit(uint quantity) view returns (uint); function toWholeShareUnit(uint quantity) view returns (uint); } interface CompetitionInterface { // EVENTS event Register(uint withId, address fund, address manager); event ClaimReward(address registrant, address fund, uint shares); // PRE, POST, INVARIANT CONDITIONS function termsAndConditionsAreSigned(address byManager, uint8 v, bytes32 r, bytes32 s) view returns (bool); function isWhitelisted(address x) view returns (bool); function isCompetitionActive() view returns (bool); // CONSTANT METHODS function getMelonAsset() view returns (address); function getRegistrantId(address x) view returns (uint); function getRegistrantFund(address x) view returns (address); function getCompetitionStatusOfRegistrants() view returns (address[], address[], bool[]); function getTimeTillEnd() view returns (uint); function getEtherValue(uint amount) view returns (uint); function calculatePayout(uint payin) view returns (uint); // PUBLIC METHODS function registerForCompetition(address fund, uint8 v, bytes32 r, bytes32 s) payable; function batchAddToWhitelist(uint maxBuyinQuantity, address[] whitelistants); function withdrawMln(address to, uint amount); function claimReward(); } interface ComplianceInterface { // PUBLIC VIEW METHODS /// @notice Checks whether investment is permitted for a participant /// @param ofParticipant Address requesting to invest in a Melon fund /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received /// @return Whether identity is eligible to invest in a Melon fund. function isInvestmentPermitted( address ofParticipant, uint256 giveQuantity, uint256 shareQuantity ) view returns (bool); /// @notice Checks whether redemption is permitted for a participant /// @param ofParticipant Address requesting to redeem from a Melon fund /// @param shareQuantity Quantity of shares times 10 ** 18 offered to redeem /// @param receiveQuantity Quantity of Melon token times 10 ** 18 requested to receive for shareQuantity /// @return Whether identity is eligible to redeem from a Melon fund. function isRedemptionPermitted( address ofParticipant, uint256 shareQuantity, uint256 receiveQuantity ) view returns (bool); } contract DBC { // MODIFIERS modifier pre_cond(bool condition) { require(condition); _; } modifier post_cond(bool condition) { _; assert(condition); } modifier invariant(bool condition) { require(condition); _; assert(condition); } } contract Owned is DBC { // FIELDS address public owner; // NON-CONSTANT METHODS function Owned() { owner = msg.sender; } function changeOwner(address ofNewOwner) pre_cond(isOwner()) { owner = ofNewOwner; } // PRE, POST, INVARIANT CONDITIONS function isOwner() internal returns (bool) { return msg.sender == owner; } } contract CompetitionCompliance is ComplianceInterface, DBC, Owned { address public competitionAddress; // CONSTRUCTOR /// @dev Constructor /// @param ofCompetition Address of the competition contract function CompetitionCompliance(address ofCompetition) public { competitionAddress = ofCompetition; } // PUBLIC VIEW METHODS /// @notice Checks whether investment is permitted for a participant /// @param ofParticipant Address requesting to invest in a Melon fund /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received /// @return Whether identity is eligible to invest in a Melon fund. function isInvestmentPermitted( address ofParticipant, uint256 giveQuantity, uint256 shareQuantity ) view returns (bool) { return competitionAddress == ofParticipant; } /// @notice Checks whether redemption is permitted for a participant /// @param ofParticipant Address requesting to redeem from a Melon fund /// @param shareQuantity Quantity of shares times 10 ** 18 offered to redeem /// @param receiveQuantity Quantity of Melon token times 10 ** 18 requested to receive for shareQuantity /// @return isEligible Whether identity is eligible to redeem from a Melon fund. function isRedemptionPermitted( address ofParticipant, uint256 shareQuantity, uint256 receiveQuantity ) view returns (bool) { return competitionAddress == ofParticipant; } /// @notice Checks whether an address is whitelisted in the competition contract and competition is active /// @param x Address /// @return Whether the address is whitelisted function isCompetitionAllowed( address x ) view returns (bool) { return CompetitionInterface(competitionAddress).isWhitelisted(x) && CompetitionInterface(competitionAddress).isCompetitionActive(); } // PUBLIC METHODS /// @notice Changes the competition address /// @param ofCompetition Address of the competition contract function changeCompetitionAddress( address ofCompetition ) pre_cond(isOwner()) { competitionAddress = ofCompetition; } } contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; function DSAuth() public { owner = msg.sender; LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } contract DSExec { function tryExec( address target, bytes calldata, uint value) internal returns (bool call_ret) { return target.call.value(value)(calldata); } function exec( address target, bytes calldata, uint value) internal { if(!tryExec(target, calldata, value)) { revert(); } } // Convenience aliases function exec( address t, bytes c ) internal { exec(t, c, 0); } function exec( address t, uint256 v ) internal { bytes memory c; exec(t, c, v); } function tryExec( address t, bytes c ) internal returns (bool) { return tryExec(t, c, 0); } function tryExec( address t, uint256 v ) internal returns (bool) { bytes memory c; return tryExec(t, c, v); } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract Asset is DSMath, ERC20Interface { // DATA STRUCTURES mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; uint public _totalSupply; // PUBLIC METHODS /** * @notice Send `_value` tokens to `_to` from `msg.sender` * @dev Transfers sender's tokens to a given address * @dev Similar to transfer(address, uint, bytes), but without _data parameter * @param _to Address of token receiver * @param _value Number of tokens to transfer * @return Returns success of function call */ function transfer(address _to, uint _value) public returns (bool success) { require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); emit Transfer(msg.sender, _to, _value); return true; } /// @notice Transfer `_value` tokens from `_from` to `_to` if `msg.sender` is allowed. /// @notice Restriction: An account can only use this function to send to itself /// @dev Allows for an approved third party to transfer tokens from one /// address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. /// @return Returns success of function call. function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(_from != address(0)); require(_to != address(0)); require(_to != address(this)); require(balances[_from] >= _value); require(allowed[_from][msg.sender] >= _value); require(balances[_to] + _value >= balances[_to]); // require(_to == msg.sender); // can only use transferFrom to send to self balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } /// @notice Allows `_spender` to transfer `_value` tokens from `msg.sender` to any address. /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. /// @return Returns success of function call. function approve(address _spender, uint _value) public returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // PUBLIC VIEW METHODS /// @dev Returns number of allowed tokens that a spender can transfer on /// behalf of a token owner. /// @param _owner Address of token owner. /// @param _spender Address of token spender. /// @return Returns remaining allowance for spender. function allowance(address _owner, address _spender) constant public returns (uint) { return allowed[_owner][_spender]; } /// @dev Returns number of tokens owned by the given address. /// @param _owner Address of token owner. /// @return Returns balance of owner. function balanceOf(address _owner) constant public returns (uint) { return balances[_owner]; } function totalSupply() view public returns (uint) { return _totalSupply; } } contract Shares is SharesInterface, Asset { // FIELDS // Constructor fields bytes32 public name; bytes8 public symbol; uint public decimal; uint public creationTime; // METHODS // CONSTRUCTOR /// @param _name Name these shares /// @param _symbol Symbol of shares /// @param _decimal Amount of decimals sharePrice is denominated in, defined to be equal as deciamls in REFERENCE_ASSET contract /// @param _creationTime Timestamp of share creation function Shares(bytes32 _name, bytes8 _symbol, uint _decimal, uint _creationTime) { name = _name; symbol = _symbol; decimal = _decimal; creationTime = _creationTime; } // PUBLIC METHODS /** * @notice Send `_value` tokens to `_to` from `msg.sender` * @dev Transfers sender's tokens to a given address * @dev Similar to transfer(address, uint, bytes), but without _data parameter * @param _to Address of token receiver * @param _value Number of tokens to transfer * @return Returns success of function call */ function transfer(address _to, uint _value) public returns (bool success) { require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); emit Transfer(msg.sender, _to, _value); return true; } // PUBLIC VIEW METHODS function getName() view returns (bytes32) { return name; } function getSymbol() view returns (bytes8) { return symbol; } function getDecimals() view returns (uint) { return decimal; } function getCreationTime() view returns (uint) { return creationTime; } function toSmallestShareUnit(uint quantity) view returns (uint) { return mul(quantity, 10 ** getDecimals()); } function toWholeShareUnit(uint quantity) view returns (uint) { return quantity / (10 ** getDecimals()); } // INTERNAL METHODS /// @param recipient Address the new shares should be sent to /// @param shareQuantity Number of shares to be created function createShares(address recipient, uint shareQuantity) internal { _totalSupply = add(_totalSupply, shareQuantity); balances[recipient] = add(balances[recipient], shareQuantity); emit Created(msg.sender, now, shareQuantity); emit Transfer(address(0), recipient, shareQuantity); } /// @param recipient Address the new shares should be taken from when destroyed /// @param shareQuantity Number of shares to be annihilated function annihilateShares(address recipient, uint shareQuantity) internal { _totalSupply = sub(_totalSupply, shareQuantity); balances[recipient] = sub(balances[recipient], shareQuantity); emit Annihilated(msg.sender, now, shareQuantity); emit Transfer(recipient, address(0), shareQuantity); } } contract Fund is DSMath, DBC, Owned, Shares, FundInterface { event OrderUpdated(address exchange, bytes32 orderId, UpdateType updateType); // TYPES struct Modules { // Describes all modular parts, standardised through an interface CanonicalPriceFeed pricefeed; // Provides all external data ComplianceInterface compliance; // Boolean functions regarding invest/redeem RiskMgmtInterface riskmgmt; // Boolean functions regarding make/take orders } struct Calculations { // List of internal calculations uint gav; // Gross asset value uint managementFee; // Time based fee uint performanceFee; // Performance based fee measured against QUOTE_ASSET uint unclaimedFees; // Fees not yet allocated to the fund manager uint nav; // Net asset value uint highWaterMark; // A record of best all-time fund performance uint totalSupply; // Total supply of shares uint timestamp; // Time when calculations are performed in seconds } enum UpdateType { make, take, cancel } enum RequestStatus { active, cancelled, executed } struct Request { // Describes and logs whenever asset enter and leave fund due to Participants address participant; // Participant in Melon fund requesting investment or redemption RequestStatus status; // Enum: active, cancelled, executed; Status of request address requestAsset; // Address of the asset being requested uint shareQuantity; // Quantity of Melon fund shares uint giveQuantity; // Quantity in Melon asset to give to Melon fund to receive shareQuantity uint receiveQuantity; // Quantity in Melon asset to receive from Melon fund for given shareQuantity uint timestamp; // Time of request creation in seconds uint atUpdateId; // Pricefeed updateId when this request was created } struct Exchange { address exchange; address exchangeAdapter; bool takesCustody; // exchange takes custody before making order } struct OpenMakeOrder { uint id; // Order Id from exchange uint expiresAt; // Timestamp when the order expires } struct Order { // Describes an order event (make or take order) address exchangeAddress; // address of the exchange this order is on bytes32 orderId; // Id as returned from exchange UpdateType updateType; // Enum: make, take (cancel should be ignored) address makerAsset; // Order maker's asset address takerAsset; // Order taker's asset uint makerQuantity; // Quantity of makerAsset to be traded uint takerQuantity; // Quantity of takerAsset to be traded uint timestamp; // Time of order creation in seconds uint fillTakerQuantity; // Quantity of takerAsset to be filled } // FIELDS // Constant fields uint public constant MAX_FUND_ASSETS = 20; // Max ownable assets by the fund supported by gas limits uint public constant ORDER_EXPIRATION_TIME = 86400; // Make order expiration time (1 day) // Constructor fields uint public MANAGEMENT_FEE_RATE; // Fee rate in QUOTE_ASSET per managed seconds in WAD uint public PERFORMANCE_FEE_RATE; // Fee rate in QUOTE_ASSET per delta improvement in WAD address public VERSION; // Address of Version contract Asset public QUOTE_ASSET; // QUOTE asset as ERC20 contract // Methods fields Modules public modules; // Struct which holds all the initialised module instances Exchange[] public exchanges; // Array containing exchanges this fund supports Calculations public atLastUnclaimedFeeAllocation; // Calculation results at last allocateUnclaimedFees() call Order[] public orders; // append-only list of makes/takes from this fund mapping (address => mapping(address => OpenMakeOrder)) public exchangesToOpenMakeOrders; // exchangeIndex to: asset to open make orders bool public isShutDown; // Security feature, if yes than investing, managing, allocateUnclaimedFees gets blocked Request[] public requests; // All the requests this fund received from participants mapping (address => bool) public isInvestAllowed; // If false, fund rejects investments from the key asset address[] public ownedAssets; // List of all assets owned by the fund or for which the fund has open make orders mapping (address => bool) public isInAssetList; // Mapping from asset to whether the asset exists in ownedAssets mapping (address => bool) public isInOpenMakeOrder; // Mapping from asset to whether the asset is in a open make order as buy asset // METHODS // CONSTRUCTOR /// @dev Should only be called via Version.setupFund(..) /// @param withName human-readable descriptive name (not necessarily unique) /// @param ofQuoteAsset Asset against which mgmt and performance fee is measured against and which can be used to invest using this single asset /// @param ofManagementFee A time based fee expressed, given in a number which is divided by 1 WAD /// @param ofPerformanceFee A time performance based fee, performance relative to ofQuoteAsset, given in a number which is divided by 1 WAD /// @param ofCompliance Address of compliance module /// @param ofRiskMgmt Address of risk management module /// @param ofPriceFeed Address of price feed module /// @param ofExchanges Addresses of exchange on which this fund can trade /// @param ofDefaultAssets Addresses of assets to enable invest for (quote asset is already enabled) /// @return Deployed Fund with manager set as ofManager function Fund( address ofManager, bytes32 withName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address ofPriceFeed, address[] ofExchanges, address[] ofDefaultAssets ) Shares(withName, "MLNF", 18, now) { require(ofManagementFee < 10 ** 18); // Require management fee to be less than 100 percent require(ofPerformanceFee < 10 ** 18); // Require performance fee to be less than 100 percent isInvestAllowed[ofQuoteAsset] = true; owner = ofManager; MANAGEMENT_FEE_RATE = ofManagementFee; // 1 percent is expressed as 0.01 * 10 ** 18 PERFORMANCE_FEE_RATE = ofPerformanceFee; // 1 percent is expressed as 0.01 * 10 ** 18 VERSION = msg.sender; modules.compliance = ComplianceInterface(ofCompliance); modules.riskmgmt = RiskMgmtInterface(ofRiskMgmt); modules.pricefeed = CanonicalPriceFeed(ofPriceFeed); // Bridged to Melon exchange interface by exchangeAdapter library for (uint i = 0; i < ofExchanges.length; ++i) { require(modules.pricefeed.exchangeIsRegistered(ofExchanges[i])); var (ofExchangeAdapter, takesCustody, ) = modules.pricefeed.getExchangeInformation(ofExchanges[i]); exchanges.push(Exchange({ exchange: ofExchanges[i], exchangeAdapter: ofExchangeAdapter, takesCustody: takesCustody })); } QUOTE_ASSET = Asset(ofQuoteAsset); // Quote Asset always in owned assets list ownedAssets.push(ofQuoteAsset); isInAssetList[ofQuoteAsset] = true; require(address(QUOTE_ASSET) == modules.pricefeed.getQuoteAsset()); // Sanity check for (uint j = 0; j < ofDefaultAssets.length; j++) { require(modules.pricefeed.assetIsRegistered(ofDefaultAssets[j])); isInvestAllowed[ofDefaultAssets[j]] = true; } atLastUnclaimedFeeAllocation = Calculations({ gav: 0, managementFee: 0, performanceFee: 0, unclaimedFees: 0, nav: 0, highWaterMark: 10 ** getDecimals(), totalSupply: _totalSupply, timestamp: now }); } // EXTERNAL METHODS // EXTERNAL : ADMINISTRATION /// @notice Enable investment in specified assets /// @param ofAssets Array of assets to enable investment in function enableInvestment(address[] ofAssets) external pre_cond(isOwner()) { for (uint i = 0; i < ofAssets.length; ++i) { require(modules.pricefeed.assetIsRegistered(ofAssets[i])); isInvestAllowed[ofAssets[i]] = true; } } /// @notice Disable investment in specified assets /// @param ofAssets Array of assets to disable investment in function disableInvestment(address[] ofAssets) external pre_cond(isOwner()) { for (uint i = 0; i < ofAssets.length; ++i) { isInvestAllowed[ofAssets[i]] = false; } } function shutDown() external pre_cond(msg.sender == VERSION) { isShutDown = true; } // EXTERNAL : PARTICIPATION /// @notice Give melon tokens to receive shares of this fund /// @dev Recommended to give some leeway in prices to account for possibly slightly changing prices /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received /// @param investmentAsset Address of asset to invest in function requestInvestment( uint giveQuantity, uint shareQuantity, address investmentAsset ) external pre_cond(!isShutDown) pre_cond(isInvestAllowed[investmentAsset]) // investment using investmentAsset has not been deactivated by the Manager pre_cond(modules.compliance.isInvestmentPermitted(msg.sender, giveQuantity, shareQuantity)) // Compliance Module: Investment permitted { requests.push(Request({ participant: msg.sender, status: RequestStatus.active, requestAsset: investmentAsset, shareQuantity: shareQuantity, giveQuantity: giveQuantity, receiveQuantity: shareQuantity, timestamp: now, atUpdateId: modules.pricefeed.getLastUpdateId() })); emit RequestUpdated(getLastRequestId()); } /// @notice Executes active investment and redemption requests, in a way that minimises information advantages of investor /// @dev Distributes melon and shares according to the request /// @param id Index of request to be executed /// @dev Active investment or redemption request executed function executeRequest(uint id) external pre_cond(!isShutDown) pre_cond(requests[id].status == RequestStatus.active) pre_cond( _totalSupply == 0 || ( now >= add(requests[id].timestamp, modules.pricefeed.getInterval()) && modules.pricefeed.getLastUpdateId() >= add(requests[id].atUpdateId, 2) ) ) // PriceFeed Module: Wait at least one interval time and two updates before continuing (unless it is the first investment) { Request request = requests[id]; var (isRecent, , ) = modules.pricefeed.getPriceInfo(address(request.requestAsset)); require(isRecent); // sharePrice quoted in QUOTE_ASSET and multiplied by 10 ** fundDecimals uint costQuantity = toWholeShareUnit(mul(request.shareQuantity, calcSharePriceAndAllocateFees())); // By definition quoteDecimals == fundDecimals if (request.requestAsset != address(QUOTE_ASSET)) { var (isPriceRecent, invertedRequestAssetPrice, requestAssetDecimal) = modules.pricefeed.getInvertedPriceInfo(request.requestAsset); if (!isPriceRecent) { revert(); } costQuantity = mul(costQuantity, invertedRequestAssetPrice) / 10 ** requestAssetDecimal; } if ( isInvestAllowed[request.requestAsset] && costQuantity <= request.giveQuantity ) { request.status = RequestStatus.executed; require(AssetInterface(request.requestAsset).transferFrom(request.participant, address(this), costQuantity)); // Allocate Value createShares(request.participant, request.shareQuantity); // Accounting if (!isInAssetList[request.requestAsset]) { ownedAssets.push(request.requestAsset); isInAssetList[request.requestAsset] = true; } } else { revert(); // Invalid Request or invalid giveQuantity / receiveQuantity } } /// @notice Cancels active investment and redemption requests /// @param id Index of request to be executed function cancelRequest(uint id) external pre_cond(requests[id].status == RequestStatus.active) // Request is active pre_cond(requests[id].participant == msg.sender || isShutDown) // Either request creator or fund is shut down { requests[id].status = RequestStatus.cancelled; } /// @notice Redeems by allocating an ownership percentage of each asset to the participant /// @dev Independent of running price feed! /// @param shareQuantity Number of shares owned by the participant, which the participant would like to redeem for individual assets /// @return Whether all assets sent to shareholder or not function redeemAllOwnedAssets(uint shareQuantity) external returns (bool success) { return emergencyRedeem(shareQuantity, ownedAssets); } // EXTERNAL : MANAGING /// @notice Universal method for calling exchange functions through adapters /// @notice See adapter contracts for parameters needed for each exchange /// @param exchangeIndex Index of the exchange in the "exchanges" array /// @param method Signature of the adapter method to call (as per ABI spec) /// @param orderAddresses [0] Order maker /// @param orderAddresses [1] Order taker /// @param orderAddresses [2] Order maker asset /// @param orderAddresses [3] Order taker asset /// @param orderAddresses [4] Fee recipient /// @param orderValues [0] Maker token quantity /// @param orderValues [1] Taker token quantity /// @param orderValues [2] Maker fee /// @param orderValues [3] Taker fee /// @param orderValues [4] Timestamp (seconds) /// @param orderValues [5] Salt/nonce /// @param orderValues [6] Fill amount: amount of taker token to be traded /// @param orderValues [7] Dexy signature mode /// @param identifier Order identifier /// @param v ECDSA recovery id /// @param r ECDSA signature output r /// @param s ECDSA signature output s function callOnExchange( uint exchangeIndex, bytes4 method, address[5] orderAddresses, uint[8] orderValues, bytes32 identifier, uint8 v, bytes32 r, bytes32 s ) external { require( modules.pricefeed.exchangeMethodIsAllowed( exchanges[exchangeIndex].exchange, method ) ); require( exchanges[exchangeIndex].exchangeAdapter.delegatecall( method, exchanges[exchangeIndex].exchange, orderAddresses, orderValues, identifier, v, r, s ) ); } function addOpenMakeOrder( address ofExchange, address ofSellAsset, uint orderId ) pre_cond(msg.sender == address(this)) { isInOpenMakeOrder[ofSellAsset] = true; exchangesToOpenMakeOrders[ofExchange][ofSellAsset].id = orderId; exchangesToOpenMakeOrders[ofExchange][ofSellAsset].expiresAt = add(now, ORDER_EXPIRATION_TIME); } function removeOpenMakeOrder( address ofExchange, address ofSellAsset ) pre_cond(msg.sender == address(this)) { delete exchangesToOpenMakeOrders[ofExchange][ofSellAsset]; } function orderUpdateHook( address ofExchange, bytes32 orderId, UpdateType updateType, address[2] orderAddresses, // makerAsset, takerAsset uint[3] orderValues // makerQuantity, takerQuantity, fillTakerQuantity (take only) ) pre_cond(msg.sender == address(this)) { // only save make/take if (updateType == UpdateType.make || updateType == UpdateType.take) { orders.push(Order({ exchangeAddress: ofExchange, orderId: orderId, updateType: updateType, makerAsset: orderAddresses[0], takerAsset: orderAddresses[1], makerQuantity: orderValues[0], takerQuantity: orderValues[1], timestamp: block.timestamp, fillTakerQuantity: orderValues[2] })); } emit OrderUpdated(ofExchange, orderId, updateType); } // PUBLIC METHODS // PUBLIC METHODS : ACCOUNTING /// @notice Calculates gross asset value of the fund /// @dev Decimals in assets must be equal to decimals in PriceFeed for all entries in AssetRegistrar /// @dev Assumes that module.pricefeed.getPriceInfo(..) returns recent prices /// @return gav Gross asset value quoted in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcGav() returns (uint gav) { // prices quoted in QUOTE_ASSET and multiplied by 10 ** assetDecimal uint[] memory allAssetHoldings = new uint[](ownedAssets.length); uint[] memory allAssetPrices = new uint[](ownedAssets.length); address[] memory tempOwnedAssets; tempOwnedAssets = ownedAssets; delete ownedAssets; for (uint i = 0; i < tempOwnedAssets.length; ++i) { address ofAsset = tempOwnedAssets[i]; // assetHoldings formatting: mul(exchangeHoldings, 10 ** assetDecimal) uint assetHoldings = add( uint(AssetInterface(ofAsset).balanceOf(address(this))), // asset base units held by fund quantityHeldInCustodyOfExchange(ofAsset) ); // assetPrice formatting: mul(exchangePrice, 10 ** assetDecimal) var (isRecent, assetPrice, assetDecimals) = modules.pricefeed.getPriceInfo(ofAsset); if (!isRecent) { revert(); } allAssetHoldings[i] = assetHoldings; allAssetPrices[i] = assetPrice; // gav as sum of mul(assetHoldings, assetPrice) with formatting: mul(mul(exchangeHoldings, exchangePrice), 10 ** shareDecimals) gav = add(gav, mul(assetHoldings, assetPrice) / (10 ** uint256(assetDecimals))); // Sum up product of asset holdings of this vault and asset prices if (assetHoldings != 0 || ofAsset == address(QUOTE_ASSET) || isInOpenMakeOrder[ofAsset]) { // Check if asset holdings is not zero or is address(QUOTE_ASSET) or in open make order ownedAssets.push(ofAsset); } else { isInAssetList[ofAsset] = false; // Remove from ownedAssets if asset holdings are zero } } emit PortfolioContent(tempOwnedAssets, allAssetHoldings, allAssetPrices); } /// @notice Add an asset to the list that this fund owns function addAssetToOwnedAssets (address ofAsset) public pre_cond(isOwner() || msg.sender == address(this)) { isInOpenMakeOrder[ofAsset] = true; if (!isInAssetList[ofAsset]) { ownedAssets.push(ofAsset); isInAssetList[ofAsset] = true; } } /** @notice Calculates unclaimed fees of the fund manager @param gav Gross asset value in QUOTE_ASSET and multiplied by 10 ** shareDecimals @return { "managementFees": "A time (seconds) based fee in QUOTE_ASSET and multiplied by 10 ** shareDecimals", "performanceFees": "A performance (rise of sharePrice measured in QUOTE_ASSET) based fee in QUOTE_ASSET and multiplied by 10 ** shareDecimals", "unclaimedfees": "The sum of both managementfee and performancefee in QUOTE_ASSET and multiplied by 10 ** shareDecimals" } */ function calcUnclaimedFees(uint gav) view returns ( uint managementFee, uint performanceFee, uint unclaimedFees) { // Management fee calculation uint timePassed = sub(now, atLastUnclaimedFeeAllocation.timestamp); uint gavPercentage = mul(timePassed, gav) / (1 years); managementFee = wmul(gavPercentage, MANAGEMENT_FEE_RATE); // Performance fee calculation // Handle potential division through zero by defining a default value uint valuePerShareExclMgmtFees = _totalSupply > 0 ? calcValuePerShare(sub(gav, managementFee), _totalSupply) : toSmallestShareUnit(1); if (valuePerShareExclMgmtFees > atLastUnclaimedFeeAllocation.highWaterMark) { uint gainInSharePrice = sub(valuePerShareExclMgmtFees, atLastUnclaimedFeeAllocation.highWaterMark); uint investmentProfits = wmul(gainInSharePrice, _totalSupply); performanceFee = wmul(investmentProfits, PERFORMANCE_FEE_RATE); } // Sum of all FEES unclaimedFees = add(managementFee, performanceFee); } /// @notice Calculates the Net asset value of this fund /// @param gav Gross asset value of this fund in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @param unclaimedFees The sum of both managementFee and performanceFee in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @return nav Net asset value in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcNav(uint gav, uint unclaimedFees) view returns (uint nav) { nav = sub(gav, unclaimedFees); } /// @notice Calculates the share price of the fund /// @dev Convention for valuePerShare (== sharePrice) formatting: mul(totalValue / numShares, 10 ** decimal), to avoid floating numbers /// @dev Non-zero share supply; value denominated in [base unit of melonAsset] /// @param totalValue the total value in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @param numShares the number of shares multiplied by 10 ** shareDecimals /// @return valuePerShare Share price denominated in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcValuePerShare(uint totalValue, uint numShares) view pre_cond(numShares > 0) returns (uint valuePerShare) { valuePerShare = toSmallestShareUnit(totalValue) / numShares; } /** @notice Calculates essential fund metrics @return { "gav": "Gross asset value of this fund denominated in [base unit of melonAsset]", "managementFee": "A time (seconds) based fee", "performanceFee": "A performance (rise of sharePrice measured in QUOTE_ASSET) based fee", "unclaimedFees": "The sum of both managementFee and performanceFee denominated in [base unit of melonAsset]", "feesShareQuantity": "The number of shares to be given as fees to the manager", "nav": "Net asset value denominated in [base unit of melonAsset]", "sharePrice": "Share price denominated in [base unit of melonAsset]" } */ function performCalculations() view returns ( uint gav, uint managementFee, uint performanceFee, uint unclaimedFees, uint feesShareQuantity, uint nav, uint sharePrice ) { gav = calcGav(); // Reflects value independent of fees (managementFee, performanceFee, unclaimedFees) = calcUnclaimedFees(gav); nav = calcNav(gav, unclaimedFees); // The value of unclaimedFees measured in shares of this fund at current value feesShareQuantity = (gav == 0) ? 0 : mul(_totalSupply, unclaimedFees) / gav; // The total share supply including the value of unclaimedFees, measured in shares of this fund uint totalSupplyAccountingForFees = add(_totalSupply, feesShareQuantity); sharePrice = _totalSupply > 0 ? calcValuePerShare(gav, totalSupplyAccountingForFees) : toSmallestShareUnit(1); // Handle potential division through zero by defining a default value } /// @notice Converts unclaimed fees of the manager into fund shares /// @return sharePrice Share price denominated in [base unit of melonAsset] function calcSharePriceAndAllocateFees() public returns (uint) { var ( gav, managementFee, performanceFee, unclaimedFees, feesShareQuantity, nav, sharePrice ) = performCalculations(); createShares(owner, feesShareQuantity); // Updates _totalSupply by creating shares allocated to manager // Update Calculations uint highWaterMark = atLastUnclaimedFeeAllocation.highWaterMark >= sharePrice ? atLastUnclaimedFeeAllocation.highWaterMark : sharePrice; atLastUnclaimedFeeAllocation = Calculations({ gav: gav, managementFee: managementFee, performanceFee: performanceFee, unclaimedFees: unclaimedFees, nav: nav, highWaterMark: highWaterMark, totalSupply: _totalSupply, timestamp: now }); emit FeesConverted(now, feesShareQuantity, unclaimedFees); emit CalculationUpdate(now, managementFee, performanceFee, nav, sharePrice, _totalSupply); return sharePrice; } // PUBLIC : REDEEMING /// @notice Redeems by allocating an ownership percentage only of requestedAssets to the participant /// @dev This works, but with loops, so only up to a certain number of assets (right now the max is 4) /// @dev Independent of running price feed! Note: if requestedAssets != ownedAssets then participant misses out on some owned value /// @param shareQuantity Number of shares owned by the participant, which the participant would like to redeem for a slice of assets /// @param requestedAssets List of addresses that consitute a subset of ownedAssets. /// @return Whether all assets sent to shareholder or not function emergencyRedeem(uint shareQuantity, address[] requestedAssets) public pre_cond(balances[msg.sender] >= shareQuantity) // sender owns enough shares returns (bool) { address ofAsset; uint[] memory ownershipQuantities = new uint[](requestedAssets.length); address[] memory redeemedAssets = new address[](requestedAssets.length); // Check whether enough assets held by fund for (uint i = 0; i < requestedAssets.length; ++i) { ofAsset = requestedAssets[i]; require(isInAssetList[ofAsset]); for (uint j = 0; j < redeemedAssets.length; j++) { if (ofAsset == redeemedAssets[j]) { revert(); } } redeemedAssets[i] = ofAsset; uint assetHoldings = add( uint(AssetInterface(ofAsset).balanceOf(address(this))), quantityHeldInCustodyOfExchange(ofAsset) ); if (assetHoldings == 0) continue; // participant's ownership percentage of asset holdings ownershipQuantities[i] = mul(assetHoldings, shareQuantity) / _totalSupply; // CRITICAL ERR: Not enough fund asset balance for owed ownershipQuantitiy, eg in case of unreturned asset quantity at address(exchanges[i].exchange) address if (uint(AssetInterface(ofAsset).balanceOf(address(this))) < ownershipQuantities[i]) { isShutDown = true; emit ErrorMessage("CRITICAL ERR: Not enough assetHoldings for owed ownershipQuantitiy"); return false; } } // Annihilate shares before external calls to prevent reentrancy annihilateShares(msg.sender, shareQuantity); // Transfer ownershipQuantity of Assets for (uint k = 0; k < requestedAssets.length; ++k) { // Failed to send owed ownershipQuantity from fund to participant ofAsset = requestedAssets[k]; if (ownershipQuantities[k] == 0) { continue; } else if (!AssetInterface(ofAsset).transfer(msg.sender, ownershipQuantities[k])) { revert(); } } emit Redeemed(msg.sender, now, shareQuantity); return true; } // PUBLIC : FEES /// @dev Quantity of asset held in exchange according to associated order id /// @param ofAsset Address of asset /// @return Quantity of input asset held in exchange function quantityHeldInCustodyOfExchange(address ofAsset) returns (uint) { uint totalSellQuantity; // quantity in custody across exchanges uint totalSellQuantityInApprove; // quantity of asset in approve (allowance) but not custody of exchange for (uint i; i < exchanges.length; i++) { if (exchangesToOpenMakeOrders[exchanges[i].exchange][ofAsset].id == 0) { continue; } var (sellAsset, , sellQuantity, ) = GenericExchangeInterface(exchanges[i].exchangeAdapter).getOrder(exchanges[i].exchange, exchangesToOpenMakeOrders[exchanges[i].exchange][ofAsset].id); if (sellQuantity == 0) { // remove id if remaining sell quantity zero (closed) delete exchangesToOpenMakeOrders[exchanges[i].exchange][ofAsset]; } totalSellQuantity = add(totalSellQuantity, sellQuantity); if (!exchanges[i].takesCustody) { totalSellQuantityInApprove += sellQuantity; } } if (totalSellQuantity == 0) { isInOpenMakeOrder[sellAsset] = false; } return sub(totalSellQuantity, totalSellQuantityInApprove); // Since quantity in approve is not actually in custody } // PUBLIC VIEW METHODS /// @notice Calculates sharePrice denominated in [base unit of melonAsset] /// @return sharePrice Share price denominated in [base unit of melonAsset] function calcSharePrice() view returns (uint sharePrice) { (, , , , , sharePrice) = performCalculations(); return sharePrice; } function getModules() view returns (address, address, address) { return ( address(modules.pricefeed), address(modules.compliance), address(modules.riskmgmt) ); } function getLastRequestId() view returns (uint) { return requests.length - 1; } function getLastOrderIndex() view returns (uint) { return orders.length - 1; } function getManager() view returns (address) { return owner; } function getOwnedAssetsLength() view returns (uint) { return ownedAssets.length; } function getExchangeInfo() view returns (address[], address[], bool[]) { address[] memory ofExchanges = new address[](exchanges.length); address[] memory ofAdapters = new address[](exchanges.length); bool[] memory takesCustody = new bool[](exchanges.length); for (uint i = 0; i < exchanges.length; i++) { ofExchanges[i] = exchanges[i].exchange; ofAdapters[i] = exchanges[i].exchangeAdapter; takesCustody[i] = exchanges[i].takesCustody; } return (ofExchanges, ofAdapters, takesCustody); } function orderExpired(address ofExchange, address ofAsset) view returns (bool) { uint expiryTime = exchangesToOpenMakeOrders[ofExchange][ofAsset].expiresAt; require(expiryTime > 0); return block.timestamp >= expiryTime; } function getOpenOrderInfo(address ofExchange, address ofAsset) view returns (uint, uint) { OpenMakeOrder order = exchangesToOpenMakeOrders[ofExchange][ofAsset]; return (order.id, order.expiresAt); } } contract Competition is CompetitionInterface, DSMath, DBC, Owned { // TYPES struct Registrant { address fund; // Address of the Melon fund address registrant; // Manager and registrant of the fund bool hasSigned; // Whether initial requirements passed and Registrant signed Terms and Conditions; uint buyinQuantity; // Quantity of buyinAsset spent uint payoutQuantity; // Quantity of payoutAsset received as prize bool isRewarded; // Is the Registrant rewarded yet } struct RegistrantId { uint id; // Actual Registrant Id bool exists; // Used to check if the mapping exists } // FIELDS // Constant fields // Competition terms and conditions as displayed on https://ipfs.io/ipfs/QmXuUfPi6xeYfuMwpVAughm7GjGUjkbEojhNR8DJqVBBxc // IPFS hash encoded using http://lenschulwitz.com/base58 bytes public constant TERMS_AND_CONDITIONS = hex"12208E21FD34B8B2409972D30326D840C9D747438A118580D6BA8C0735ED53810491"; uint public MELON_BASE_UNIT = 10 ** 18; // Constructor fields address public custodian; // Address of the custodian which holds the funds sent uint public startTime; // Competition start time in seconds (Temporarily Set) uint public endTime; // Competition end time in seconds uint public payoutRate; // Fixed MLN - Ether conversion rate uint public bonusRate; // Bonus multiplier uint public totalMaxBuyin; // Limit amount of deposit to participate in competition (Valued in Ether) uint public currentTotalBuyin; // Total buyin till now uint public maxRegistrants; // Limit number of participate in competition uint public prizeMoneyAsset; // Equivalent to payoutAsset uint public prizeMoneyQuantity; // Total prize money pool address public MELON_ASSET; // Adresss of Melon asset contract ERC20Interface public MELON_CONTRACT; // Melon as ERC20 contract address public COMPETITION_VERSION; // Version contract address // Methods fields Registrant[] public registrants; // List of all registrants, can be externally accessed mapping (address => address) public registeredFundToRegistrants; // For fund address indexed accessing of registrant addresses mapping(address => RegistrantId) public registrantToRegistrantIds; // For registrant address indexed accessing of registrant ids mapping(address => uint) public whitelistantToMaxBuyin; // For registrant address to respective max buyIn cap (Valued in Ether) //EVENTS event Register(uint withId, address fund, address manager); // METHODS // CONSTRUCTOR function Competition( address ofMelonAsset, address ofCompetitionVersion, address ofCustodian, uint ofStartTime, uint ofEndTime, uint ofPayoutRate, uint ofTotalMaxBuyin, uint ofMaxRegistrants ) { MELON_ASSET = ofMelonAsset; MELON_CONTRACT = ERC20Interface(MELON_ASSET); COMPETITION_VERSION = ofCompetitionVersion; custodian = ofCustodian; startTime = ofStartTime; endTime = ofEndTime; payoutRate = ofPayoutRate; totalMaxBuyin = ofTotalMaxBuyin; maxRegistrants = ofMaxRegistrants; } // PRE, POST, INVARIANT CONDITIONS /// @dev Proofs that terms and conditions have been read and understood /// @param byManager Address of the fund manager, as used in the ipfs-frontend /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s /// @return Whether or not terms and conditions have been read and understood function termsAndConditionsAreSigned(address byManager, uint8 v, bytes32 r, bytes32 s) view returns (bool) { return ecrecover( // Parity does prepend \x19Ethereum Signed Message:\n{len(message)} before signing. // Signature order has also been changed in 1.6.7 and upcoming 1.7.x, // it will return rsv (same as geth; where v is [27, 28]). // Note that if you are using ecrecover, v will be either "00" or "01". // As a result, in order to use this value, you will have to parse it to an // integer and then add 27. This will result in either a 27 or a 28. // https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsign keccak256("\x19Ethereum Signed Message:\n34", TERMS_AND_CONDITIONS), v, r, s ) == byManager; // Has sender signed TERMS_AND_CONDITIONS } /// @dev Whether message sender is KYC verified through CERTIFIER /// @param x Address to be checked for KYC verification function isWhitelisted(address x) view returns (bool) { return whitelistantToMaxBuyin[x] > 0; } /// @dev Whether the competition is on-going function isCompetitionActive() view returns (bool) { return now >= startTime && now < endTime; } // CONSTANT METHODS function getMelonAsset() view returns (address) { return MELON_ASSET; } /// @return Get RegistrantId from registrant address function getRegistrantId(address x) view returns (uint) { return registrantToRegistrantIds[x].id; } /// @return Address of the fund registered by the registrant address function getRegistrantFund(address x) view returns (address) { return registrants[getRegistrantId(x)].fund; } /// @return Get time to end of the competition function getTimeTillEnd() view returns (uint) { if (now > endTime) { return 0; } return sub(endTime, now); } /// @return Get value of MLN amount in Ether function getEtherValue(uint amount) view returns (uint) { address feedAddress = Version(COMPETITION_VERSION).CANONICAL_PRICEFEED(); var (isRecent, price, ) = CanonicalPriceFeed(feedAddress).getPriceInfo(MELON_ASSET); if (!isRecent) { revert(); } return mul(price, amount) / 10 ** 18; } /// @return Calculated payout in MLN with bonus for payin in Ether function calculatePayout(uint payin) view returns (uint payoutQuantity) { payoutQuantity = mul(payin, payoutRate) / 10 ** 18; } /** @notice Returns an array of fund addresses and an associated array of whether competing and whether disqualified @return { "fundAddrs": "Array of addresses of Melon Funds", "fundRegistrants": "Array of addresses of Melon fund managers, as used in the ipfs-frontend", } */ function getCompetitionStatusOfRegistrants() view returns( address[], address[], bool[] ) { address[] memory fundAddrs = new address[](registrants.length); address[] memory fundRegistrants = new address[](registrants.length); bool[] memory isRewarded = new bool[](registrants.length); for (uint i = 0; i < registrants.length; i++) { fundAddrs[i] = registrants[i].fund; fundRegistrants[i] = registrants[i].registrant; isRewarded[i] = registrants[i].isRewarded; } return (fundAddrs, fundRegistrants, isRewarded); } // NON-CONSTANT METHODS /// @notice Register to take part in the competition /// @dev Check if the fund address is actually from the Competition Version /// @param fund Address of the Melon fund /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s function registerForCompetition( address fund, uint8 v, bytes32 r, bytes32 s ) payable pre_cond(isCompetitionActive() && !Version(COMPETITION_VERSION).isShutDown()) pre_cond(termsAndConditionsAreSigned(msg.sender, v, r, s) && isWhitelisted(msg.sender)) { require(registeredFundToRegistrants[fund] == address(0) && registrantToRegistrantIds[msg.sender].exists == false); require(add(currentTotalBuyin, msg.value) <= totalMaxBuyin && registrants.length < maxRegistrants); require(msg.value <= whitelistantToMaxBuyin[msg.sender]); require(Version(COMPETITION_VERSION).getFundByManager(msg.sender) == fund); // Calculate Payout Quantity, invest the quantity in registrant's fund uint payoutQuantity = calculatePayout(msg.value); registeredFundToRegistrants[fund] = msg.sender; registrantToRegistrantIds[msg.sender] = RegistrantId({id: registrants.length, exists: true}); currentTotalBuyin = add(currentTotalBuyin, msg.value); FundInterface fundContract = FundInterface(fund); MELON_CONTRACT.approve(fund, payoutQuantity); // Give payoutRequest MLN in return for msg.value fundContract.requestInvestment(payoutQuantity, getEtherValue(payoutQuantity), MELON_ASSET); fundContract.executeRequest(fundContract.getLastRequestId()); custodian.transfer(msg.value); // Emit Register event emit Register(registrants.length, fund, msg.sender); registrants.push(Registrant({ fund: fund, registrant: msg.sender, hasSigned: true, buyinQuantity: msg.value, payoutQuantity: payoutQuantity, isRewarded: false })); } /// @notice Add batch addresses to whitelist with set maxBuyinQuantity /// @dev Only the owner can call this function /// @param maxBuyinQuantity Quantity of payoutAsset received as prize /// @param whitelistants Performance of Melon fund at competition endTime; Can be changed for any other comparison metric function batchAddToWhitelist( uint maxBuyinQuantity, address[] whitelistants ) pre_cond(isOwner()) pre_cond(now < endTime) { for (uint i = 0; i < whitelistants.length; ++i) { whitelistantToMaxBuyin[whitelistants[i]] = maxBuyinQuantity; } } /// @notice Withdraw MLN /// @dev Only the owner can call this function function withdrawMln(address to, uint amount) pre_cond(isOwner()) { MELON_CONTRACT.transfer(to, amount); } /// @notice Claim Reward function claimReward() pre_cond(getRegistrantFund(msg.sender) != address(0)) { require(block.timestamp >= endTime || Version(COMPETITION_VERSION).isShutDown()); Registrant registrant = registrants[getRegistrantId(msg.sender)]; require(registrant.isRewarded == false); registrant.isRewarded = true; // Is this safe to assume this or should we transfer all the balance instead? uint balance = AssetInterface(registrant.fund).balanceOf(address(this)); require(AssetInterface(registrant.fund).transfer(registrant.registrant, balance)); // Emit ClaimedReward event emit ClaimReward(msg.sender, registrant.fund, balance); } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } contract DSGroup is DSExec, DSNote { address[] public members; uint public quorum; uint public window; uint public actionCount; mapping (uint => Action) public actions; mapping (uint => mapping (address => bool)) public confirmedBy; mapping (address => bool) public isMember; // Legacy events event Proposed (uint id, bytes calldata); event Confirmed (uint id, address member); event Triggered (uint id); struct Action { address target; bytes calldata; uint value; uint confirmations; uint deadline; bool triggered; } function DSGroup( address[] members_, uint quorum_, uint window_ ) { members = members_; quorum = quorum_; window = window_; for (uint i = 0; i < members.length; i++) { isMember[members[i]] = true; } } function memberCount() constant returns (uint) { return members.length; } function target(uint id) constant returns (address) { return actions[id].target; } function calldata(uint id) constant returns (bytes) { return actions[id].calldata; } function value(uint id) constant returns (uint) { return actions[id].value; } function confirmations(uint id) constant returns (uint) { return actions[id].confirmations; } function deadline(uint id) constant returns (uint) { return actions[id].deadline; } function triggered(uint id) constant returns (bool) { return actions[id].triggered; } function confirmed(uint id) constant returns (bool) { return confirmations(id) >= quorum; } function expired(uint id) constant returns (bool) { return now > deadline(id); } function deposit() note payable { } function propose( address target, bytes calldata, uint value ) onlyMembers note returns (uint id) { id = ++actionCount; actions[id].target = target; actions[id].calldata = calldata; actions[id].value = value; actions[id].deadline = now + window; Proposed(id, calldata); } function confirm(uint id) onlyMembers onlyActive(id) note { assert(!confirmedBy[id][msg.sender]); confirmedBy[id][msg.sender] = true; actions[id].confirmations++; Confirmed(id, msg.sender); } function trigger(uint id) onlyMembers onlyActive(id) note { assert(confirmed(id)); actions[id].triggered = true; exec(actions[id].target, actions[id].calldata, actions[id].value); Triggered(id); } modifier onlyMembers { assert(isMember[msg.sender]); _; } modifier onlyActive(uint id) { assert(!expired(id)); assert(!triggered(id)); _; } //------------------------------------------------------------------ // Legacy functions //------------------------------------------------------------------ function getInfo() constant returns ( uint quorum_, uint memberCount, uint window_, uint actionCount_ ) { return (quorum, members.length, window, actionCount); } function getActionStatus(uint id) constant returns ( uint confirmations, uint deadline, bool triggered, address target, uint value ) { return ( actions[id].confirmations, actions[id].deadline, actions[id].triggered, actions[id].target, actions[id].value ); } } contract DSGroupFactory is DSNote { mapping (address => bool) public isGroup; function newGroup( address[] members, uint quorum, uint window ) note returns (DSGroup group) { group = new DSGroup(members, quorum, window); isGroup[group] = true; } } contract DSThing is DSAuth, DSNote, DSMath { function S(string s) internal pure returns (bytes4) { return bytes4(keccak256(s)); } } interface GenericExchangeInterface { // EVENTS event OrderUpdated(uint id); // METHODS // EXTERNAL METHODS function makeOrder( address onExchange, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) external returns (uint); function takeOrder(address onExchange, uint id, uint quantity) external returns (bool); function cancelOrder(address onExchange, uint id) external returns (bool); // PUBLIC METHODS // PUBLIC VIEW METHODS function isApproveOnly() view returns (bool); function getLastOrderId(address onExchange) view returns (uint); function isActive(address onExchange, uint id) view returns (bool); function getOwner(address onExchange, uint id) view returns (address); function getOrder(address onExchange, uint id) view returns (address, address, uint, uint); function getTimestamp(address onExchange, uint id) view returns (uint); } contract CanonicalRegistrar is DSThing, DBC { // TYPES struct Asset { bool exists; // True if asset is registered here bytes32 name; // Human-readable name of the Asset as in ERC223 token standard bytes8 symbol; // Human-readable symbol of the Asset as in ERC223 token standard uint decimals; // Decimal, order of magnitude of precision, of the Asset as in ERC223 token standard string url; // URL for additional information of Asset string ipfsHash; // Same as url but for ipfs address breakIn; // Break in contract on destination chain address breakOut; // Break out contract on this chain; A way to leave uint[] standards; // compliance with standards like ERC20, ERC223, ERC777, etc. (the uint is the standard number) bytes4[] functionSignatures; // Whitelisted function signatures that can be called using `useExternalFunction` in Fund contract. Note: Adhere to a naming convention for `Fund<->Asset` as much as possible. I.e. name same concepts with the same functionSignature. uint price; // Price of asset quoted against `QUOTE_ASSET` * 10 ** decimals uint timestamp; // Timestamp of last price update of this asset } struct Exchange { bool exists; address adapter; // adapter contract for this exchange // One-time note: takesCustody is inverse case of isApproveOnly bool takesCustody; // True in case of exchange implementation which requires are approved when an order is made instead of transfer bytes4[] functionSignatures; // Whitelisted function signatures that can be called using `useExternalFunction` in Fund contract. Note: Adhere to a naming convention for `Fund<->ExchangeAdapter` as much as possible. I.e. name same concepts with the same functionSignature. } // TODO: populate each field here // TODO: add whitelistFunction function // FIELDS // Methods fields mapping (address => Asset) public assetInformation; address[] public registeredAssets; mapping (address => Exchange) public exchangeInformation; address[] public registeredExchanges; // METHODS // PUBLIC METHODS /// @notice Registers an Asset information entry /// @dev Pre: Only registrar owner should be able to register /// @dev Post: Address ofAsset is registered /// @param ofAsset Address of asset to be registered /// @param inputName Human-readable name of the Asset as in ERC223 token standard /// @param inputSymbol Human-readable symbol of the Asset as in ERC223 token standard /// @param inputDecimals Human-readable symbol of the Asset as in ERC223 token standard /// @param inputUrl Url for extended information of the asset /// @param inputIpfsHash Same as url but for ipfs /// @param breakInBreakOut Address of break in and break out contracts on destination chain /// @param inputStandards Integers of EIP standards this asset adheres to /// @param inputFunctionSignatures Function signatures for whitelisted asset functions function registerAsset( address ofAsset, bytes32 inputName, bytes8 inputSymbol, uint inputDecimals, string inputUrl, string inputIpfsHash, address[2] breakInBreakOut, uint[] inputStandards, bytes4[] inputFunctionSignatures ) auth pre_cond(!assetInformation[ofAsset].exists) { assetInformation[ofAsset].exists = true; registeredAssets.push(ofAsset); updateAsset( ofAsset, inputName, inputSymbol, inputDecimals, inputUrl, inputIpfsHash, breakInBreakOut, inputStandards, inputFunctionSignatures ); assert(assetInformation[ofAsset].exists); } /// @notice Register an exchange information entry /// @dev Pre: Only registrar owner should be able to register /// @dev Post: Address ofExchange is registered /// @param ofExchange Address of the exchange /// @param ofExchangeAdapter Address of exchange adapter for this exchange /// @param inputTakesCustody Whether this exchange takes custody of tokens before trading /// @param inputFunctionSignatures Function signatures for whitelisted exchange functions function registerExchange( address ofExchange, address ofExchangeAdapter, bool inputTakesCustody, bytes4[] inputFunctionSignatures ) auth pre_cond(!exchangeInformation[ofExchange].exists) { exchangeInformation[ofExchange].exists = true; registeredExchanges.push(ofExchange); updateExchange( ofExchange, ofExchangeAdapter, inputTakesCustody, inputFunctionSignatures ); assert(exchangeInformation[ofExchange].exists); } /// @notice Updates description information of a registered Asset /// @dev Pre: Owner can change an existing entry /// @dev Post: Changed Name, Symbol, URL and/or IPFSHash /// @param ofAsset Address of the asset to be updated /// @param inputName Human-readable name of the Asset as in ERC223 token standard /// @param inputSymbol Human-readable symbol of the Asset as in ERC223 token standard /// @param inputUrl Url for extended information of the asset /// @param inputIpfsHash Same as url but for ipfs function updateAsset( address ofAsset, bytes32 inputName, bytes8 inputSymbol, uint inputDecimals, string inputUrl, string inputIpfsHash, address[2] ofBreakInBreakOut, uint[] inputStandards, bytes4[] inputFunctionSignatures ) auth pre_cond(assetInformation[ofAsset].exists) { Asset asset = assetInformation[ofAsset]; asset.name = inputName; asset.symbol = inputSymbol; asset.decimals = inputDecimals; asset.url = inputUrl; asset.ipfsHash = inputIpfsHash; asset.breakIn = ofBreakInBreakOut[0]; asset.breakOut = ofBreakInBreakOut[1]; asset.standards = inputStandards; asset.functionSignatures = inputFunctionSignatures; } function updateExchange( address ofExchange, address ofExchangeAdapter, bool inputTakesCustody, bytes4[] inputFunctionSignatures ) auth pre_cond(exchangeInformation[ofExchange].exists) { Exchange exchange = exchangeInformation[ofExchange]; exchange.adapter = ofExchangeAdapter; exchange.takesCustody = inputTakesCustody; exchange.functionSignatures = inputFunctionSignatures; } // TODO: check max size of array before remaking this becomes untenable /// @notice Deletes an existing entry /// @dev Owner can delete an existing entry /// @param ofAsset address for which specific information is requested function removeAsset( address ofAsset, uint assetIndex ) auth pre_cond(assetInformation[ofAsset].exists) { require(registeredAssets[assetIndex] == ofAsset); delete assetInformation[ofAsset]; // Sets exists boolean to false delete registeredAssets[assetIndex]; for (uint i = assetIndex; i < registeredAssets.length-1; i++) { registeredAssets[i] = registeredAssets[i+1]; } registeredAssets.length--; assert(!assetInformation[ofAsset].exists); } /// @notice Deletes an existing entry /// @dev Owner can delete an existing entry /// @param ofExchange address for which specific information is requested /// @param exchangeIndex index of the exchange in array function removeExchange( address ofExchange, uint exchangeIndex ) auth pre_cond(exchangeInformation[ofExchange].exists) { require(registeredExchanges[exchangeIndex] == ofExchange); delete exchangeInformation[ofExchange]; delete registeredExchanges[exchangeIndex]; for (uint i = exchangeIndex; i < registeredExchanges.length-1; i++) { registeredExchanges[i] = registeredExchanges[i+1]; } registeredExchanges.length--; assert(!exchangeInformation[ofExchange].exists); } // PUBLIC VIEW METHODS // get asset specific information function getName(address ofAsset) view returns (bytes32) { return assetInformation[ofAsset].name; } function getSymbol(address ofAsset) view returns (bytes8) { return assetInformation[ofAsset].symbol; } function getDecimals(address ofAsset) view returns (uint) { return assetInformation[ofAsset].decimals; } function assetIsRegistered(address ofAsset) view returns (bool) { return assetInformation[ofAsset].exists; } function getRegisteredAssets() view returns (address[]) { return registeredAssets; } function assetMethodIsAllowed( address ofAsset, bytes4 querySignature ) returns (bool) { bytes4[] memory signatures = assetInformation[ofAsset].functionSignatures; for (uint i = 0; i < signatures.length; i++) { if (signatures[i] == querySignature) { return true; } } return false; } // get exchange-specific information function exchangeIsRegistered(address ofExchange) view returns (bool) { return exchangeInformation[ofExchange].exists; } function getRegisteredExchanges() view returns (address[]) { return registeredExchanges; } function getExchangeInformation(address ofExchange) view returns (address, bool) { Exchange exchange = exchangeInformation[ofExchange]; return ( exchange.adapter, exchange.takesCustody ); } function getExchangeFunctionSignatures(address ofExchange) view returns (bytes4[]) { return exchangeInformation[ofExchange].functionSignatures; } function exchangeMethodIsAllowed( address ofExchange, bytes4 querySignature ) returns (bool) { bytes4[] memory signatures = exchangeInformation[ofExchange].functionSignatures; for (uint i = 0; i < signatures.length; i++) { if (signatures[i] == querySignature) { return true; } } return false; } } interface SimplePriceFeedInterface { // EVENTS event PriceUpdated(bytes32 hash); // PUBLIC METHODS function update(address[] ofAssets, uint[] newPrices) external; // PUBLIC VIEW METHODS // Get price feed operation specific information function getQuoteAsset() view returns (address); function getLastUpdateId() view returns (uint); // Get asset specific information as updated in price feed function getPrice(address ofAsset) view returns (uint price, uint timestamp); function getPrices(address[] ofAssets) view returns (uint[] prices, uint[] timestamps); } contract SimplePriceFeed is SimplePriceFeedInterface, DSThing, DBC { // TYPES struct Data { uint price; uint timestamp; } // FIELDS mapping(address => Data) public assetsToPrices; // Constructor fields address public QUOTE_ASSET; // Asset of a portfolio against which all other assets are priced // Contract-level variables uint public updateId; // Update counter for this pricefeed; used as a check during investment CanonicalRegistrar public registrar; CanonicalPriceFeed public superFeed; // METHODS // CONSTRUCTOR /// @param ofQuoteAsset Address of quote asset /// @param ofRegistrar Address of canonical registrar /// @param ofSuperFeed Address of superfeed function SimplePriceFeed( address ofRegistrar, address ofQuoteAsset, address ofSuperFeed ) { registrar = CanonicalRegistrar(ofRegistrar); QUOTE_ASSET = ofQuoteAsset; superFeed = CanonicalPriceFeed(ofSuperFeed); } // EXTERNAL METHODS /// @dev Only Owner; Same sized input arrays /// @dev Updates price of asset relative to QUOTE_ASSET /** Ex: * Let QUOTE_ASSET == MLN (base units), let asset == EUR-T, * let Value of 1 EUR-T := 1 EUR == 0.080456789 MLN, hence price 0.080456789 MLN / EUR-T * and let EUR-T decimals == 8. * Input would be: information[EUR-T].price = 8045678 [MLN/ (EUR-T * 10**8)] */ /// @param ofAssets list of asset addresses /// @param newPrices list of prices for each of the assets function update(address[] ofAssets, uint[] newPrices) external auth { _updatePrices(ofAssets, newPrices); } // PUBLIC VIEW METHODS // Get pricefeed specific information function getQuoteAsset() view returns (address) { return QUOTE_ASSET; } function getLastUpdateId() view returns (uint) { return updateId; } /** @notice Gets price of an asset multiplied by ten to the power of assetDecimals @dev Asset has been registered @param ofAsset Asset for which price should be returned @return { "price": "Price formatting: mul(exchangePrice, 10 ** decimal), to avoid floating numbers", "timestamp": "When the asset's price was updated" } */ function getPrice(address ofAsset) view returns (uint price, uint timestamp) { Data data = assetsToPrices[ofAsset]; return (data.price, data.timestamp); } /** @notice Price of a registered asset in format (bool areRecent, uint[] prices, uint[] decimals) @dev Convention for price formatting: mul(price, 10 ** decimal), to avoid floating numbers @param ofAssets Assets for which prices should be returned @return { "prices": "Array of prices", "timestamps": "Array of timestamps", } */ function getPrices(address[] ofAssets) view returns (uint[], uint[]) { uint[] memory prices = new uint[](ofAssets.length); uint[] memory timestamps = new uint[](ofAssets.length); for (uint i; i < ofAssets.length; i++) { var (price, timestamp) = getPrice(ofAssets[i]); prices[i] = price; timestamps[i] = timestamp; } return (prices, timestamps); } // INTERNAL METHODS /// @dev Internal so that feeds inheriting this one are not obligated to have an exposed update(...) method, but can still perform updates function _updatePrices(address[] ofAssets, uint[] newPrices) internal pre_cond(ofAssets.length == newPrices.length) { updateId++; for (uint i = 0; i < ofAssets.length; ++i) { require(registrar.assetIsRegistered(ofAssets[i])); require(assetsToPrices[ofAssets[i]].timestamp != now); // prevent two updates in one block assetsToPrices[ofAssets[i]].timestamp = now; assetsToPrices[ofAssets[i]].price = newPrices[i]; } emit PriceUpdated(keccak256(ofAssets, newPrices)); } } contract StakingPriceFeed is SimplePriceFeed { OperatorStaking public stakingContract; AssetInterface public stakingToken; // CONSTRUCTOR /// @param ofQuoteAsset Address of quote asset /// @param ofRegistrar Address of canonical registrar /// @param ofSuperFeed Address of superfeed function StakingPriceFeed( address ofRegistrar, address ofQuoteAsset, address ofSuperFeed ) SimplePriceFeed(ofRegistrar, ofQuoteAsset, ofSuperFeed) { stakingContract = OperatorStaking(ofSuperFeed); // canonical feed *is* staking contract stakingToken = AssetInterface(stakingContract.stakingToken()); } // EXTERNAL METHODS /// @param amount Number of tokens to stake for this feed /// @param data Data may be needed for some future applications (can be empty for now) function depositStake(uint amount, bytes data) external auth { require(stakingToken.transferFrom(msg.sender, address(this), amount)); require(stakingToken.approve(stakingContract, amount)); stakingContract.stake(amount, data); } /// @param amount Number of tokens to unstake for this feed /// @param data Data may be needed for some future applications (can be empty for now) function unstake(uint amount, bytes data) external auth { stakingContract.unstake(amount, data); } function withdrawStake() external auth { uint amountToWithdraw = stakingContract.stakeToWithdraw(address(this)); stakingContract.withdrawStake(); require(stakingToken.transfer(msg.sender, amountToWithdraw)); } } interface RiskMgmtInterface { // METHODS // PUBLIC VIEW METHODS /// @notice Checks if the makeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If makeOrder is permitted function isMakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool); /// @notice Checks if the takeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If takeOrder is permitted function isTakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool); } contract OperatorStaking is DBC { // EVENTS event Staked(address indexed user, uint256 amount, uint256 total, bytes data); event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data); event StakeBurned(address indexed user, uint256 amount, bytes data); // TYPES struct StakeData { uint amount; address staker; } // Circular linked list struct Node { StakeData data; uint prev; uint next; } // FIELDS // INTERNAL FIELDS Node[] internal stakeNodes; // Sorted circular linked list nodes containing stake data (Built on top https://programtheblockchain.com/posts/2018/03/30/storage-patterns-doubly-linked-list/) // PUBLIC FIELDS uint public minimumStake; uint public numOperators; uint public withdrawalDelay; mapping (address => bool) public isRanked; mapping (address => uint) public latestUnstakeTime; mapping (address => uint) public stakeToWithdraw; mapping (address => uint) public stakedAmounts; uint public numStakers; // Current number of stakers (Needed because of array holes) AssetInterface public stakingToken; // TODO: consider renaming "operator" depending on how this is implemented // (i.e. is pricefeed staking itself?) function OperatorStaking( AssetInterface _stakingToken, uint _minimumStake, uint _numOperators, uint _withdrawalDelay ) public { require(address(_stakingToken) != address(0)); stakingToken = _stakingToken; minimumStake = _minimumStake; numOperators = _numOperators; withdrawalDelay = _withdrawalDelay; StakeData memory temp = StakeData({ amount: 0, staker: address(0) }); stakeNodes.push(Node(temp, 0, 0)); } // METHODS : STAKING function stake( uint amount, bytes data ) public pre_cond(amount >= minimumStake) { stakedAmounts[msg.sender] += amount; updateStakerRanking(msg.sender); require(stakingToken.transferFrom(msg.sender, address(this), amount)); } function unstake( uint amount, bytes data ) public { uint preStake = stakedAmounts[msg.sender]; uint postStake = preStake - amount; require(postStake >= minimumStake || postStake == 0); require(stakedAmounts[msg.sender] >= amount); latestUnstakeTime[msg.sender] = block.timestamp; stakedAmounts[msg.sender] -= amount; stakeToWithdraw[msg.sender] += amount; updateStakerRanking(msg.sender); emit Unstaked(msg.sender, amount, stakedAmounts[msg.sender], data); } function withdrawStake() public pre_cond(stakeToWithdraw[msg.sender] > 0) pre_cond(block.timestamp >= latestUnstakeTime[msg.sender] + withdrawalDelay) { uint amount = stakeToWithdraw[msg.sender]; stakeToWithdraw[msg.sender] = 0; require(stakingToken.transfer(msg.sender, amount)); } // VIEW FUNCTIONS function isValidNode(uint id) view returns (bool) { // 0 is a sentinel and therefore invalid. // A valid node is the head or has a previous node. return id != 0 && (id == stakeNodes[0].next || stakeNodes[id].prev != 0); } function searchNode(address staker) view returns (uint) { uint current = stakeNodes[0].next; while (isValidNode(current)) { if (staker == stakeNodes[current].data.staker) { return current; } current = stakeNodes[current].next; } return 0; } function isOperator(address user) view returns (bool) { address[] memory operators = getOperators(); for (uint i; i < operators.length; i++) { if (operators[i] == user) { return true; } } return false; } function getOperators() view returns (address[]) { uint arrLength = (numOperators > numStakers) ? numStakers : numOperators; address[] memory operators = new address[](arrLength); uint current = stakeNodes[0].next; for (uint i; i < arrLength; i++) { operators[i] = stakeNodes[current].data.staker; current = stakeNodes[current].next; } return operators; } function getStakersAndAmounts() view returns (address[], uint[]) { address[] memory stakers = new address[](numStakers); uint[] memory amounts = new uint[](numStakers); uint current = stakeNodes[0].next; for (uint i; i < numStakers; i++) { stakers[i] = stakeNodes[current].data.staker; amounts[i] = stakeNodes[current].data.amount; current = stakeNodes[current].next; } return (stakers, amounts); } function totalStakedFor(address user) view returns (uint) { return stakedAmounts[user]; } // INTERNAL METHODS // DOUBLY-LINKED LIST function insertNodeSorted(uint amount, address staker) internal returns (uint) { uint current = stakeNodes[0].next; if (current == 0) return insertNodeAfter(0, amount, staker); while (isValidNode(current)) { if (amount > stakeNodes[current].data.amount) { break; } current = stakeNodes[current].next; } return insertNodeBefore(current, amount, staker); } function insertNodeAfter(uint id, uint amount, address staker) internal returns (uint newID) { // 0 is allowed here to insert at the beginning. require(id == 0 || isValidNode(id)); Node storage node = stakeNodes[id]; stakeNodes.push(Node({ data: StakeData(amount, staker), prev: id, next: node.next })); newID = stakeNodes.length - 1; stakeNodes[node.next].prev = newID; node.next = newID; numStakers++; } function insertNodeBefore(uint id, uint amount, address staker) internal returns (uint) { return insertNodeAfter(stakeNodes[id].prev, amount, staker); } function removeNode(uint id) internal { require(isValidNode(id)); Node storage node = stakeNodes[id]; stakeNodes[node.next].prev = node.prev; stakeNodes[node.prev].next = node.next; delete stakeNodes[id]; numStakers--; } // UPDATING OPERATORS function updateStakerRanking(address _staker) internal { uint newStakedAmount = stakedAmounts[_staker]; if (newStakedAmount == 0) { isRanked[_staker] = false; removeStakerFromArray(_staker); } else if (isRanked[_staker]) { removeStakerFromArray(_staker); insertNodeSorted(newStakedAmount, _staker); } else { isRanked[_staker] = true; insertNodeSorted(newStakedAmount, _staker); } } function removeStakerFromArray(address _staker) internal { uint id = searchNode(_staker); require(id > 0); removeNode(id); } } contract CanonicalPriceFeed is OperatorStaking, SimplePriceFeed, CanonicalRegistrar { // EVENTS event SetupPriceFeed(address ofPriceFeed); struct HistoricalPrices { address[] assets; uint[] prices; uint timestamp; } // FIELDS bool public updatesAreAllowed = true; uint public minimumPriceCount = 1; uint public VALIDITY; uint public INTERVAL; mapping (address => bool) public isStakingFeed; // If the Staking Feed has been created through this contract HistoricalPrices[] public priceHistory; // METHODS // CONSTRUCTOR /// @dev Define and register a quote asset against which all prices are measured/based against /// @param ofStakingAsset Address of staking asset (may or may not be quoteAsset) /// @param ofQuoteAsset Address of quote asset /// @param quoteAssetName Name of quote asset /// @param quoteAssetSymbol Symbol for quote asset /// @param quoteAssetDecimals Decimal places for quote asset /// @param quoteAssetUrl URL related to quote asset /// @param quoteAssetIpfsHash IPFS hash associated with quote asset /// @param quoteAssetBreakInBreakOut Break-in/break-out for quote asset on destination chain /// @param quoteAssetStandards EIP standards quote asset adheres to /// @param quoteAssetFunctionSignatures Whitelisted functions of quote asset contract // /// @param interval Number of seconds between pricefeed updates (this interval is not enforced on-chain, but should be followed by the datafeed maintainer) // /// @param validity Number of seconds that datafeed update information is valid for /// @param ofGovernance Address of contract governing the Canonical PriceFeed function CanonicalPriceFeed( address ofStakingAsset, address ofQuoteAsset, // Inital entry in asset registrar contract is Melon (QUOTE_ASSET) bytes32 quoteAssetName, bytes8 quoteAssetSymbol, uint quoteAssetDecimals, string quoteAssetUrl, string quoteAssetIpfsHash, address[2] quoteAssetBreakInBreakOut, uint[] quoteAssetStandards, bytes4[] quoteAssetFunctionSignatures, uint[2] updateInfo, // interval, validity uint[3] stakingInfo, // minStake, numOperators, unstakeDelay address ofGovernance ) OperatorStaking( AssetInterface(ofStakingAsset), stakingInfo[0], stakingInfo[1], stakingInfo[2] ) SimplePriceFeed(address(this), ofQuoteAsset, address(0)) { registerAsset( ofQuoteAsset, quoteAssetName, quoteAssetSymbol, quoteAssetDecimals, quoteAssetUrl, quoteAssetIpfsHash, quoteAssetBreakInBreakOut, quoteAssetStandards, quoteAssetFunctionSignatures ); INTERVAL = updateInfo[0]; VALIDITY = updateInfo[1]; setOwner(ofGovernance); } // EXTERNAL METHODS /// @notice Create a new StakingPriceFeed function setupStakingPriceFeed() external { address ofStakingPriceFeed = new StakingPriceFeed( address(this), stakingToken, address(this) ); isStakingFeed[ofStakingPriceFeed] = true; StakingPriceFeed(ofStakingPriceFeed).setOwner(msg.sender); emit SetupPriceFeed(ofStakingPriceFeed); } /// @dev override inherited update function to prevent manual update from authority function update(address[] ofAssets, uint[] newPrices) external { revert(); } /// @dev Burn state for a pricefeed operator /// @param user Address of pricefeed operator to burn the stake from function burnStake(address user) external auth { uint totalToBurn = add(stakedAmounts[user], stakeToWithdraw[user]); stakedAmounts[user] = 0; stakeToWithdraw[user] = 0; updateStakerRanking(user); emit StakeBurned(user, totalToBurn, ""); } // PUBLIC METHODS // STAKING function stake( uint amount, bytes data ) public pre_cond(isStakingFeed[msg.sender]) { OperatorStaking.stake(amount, data); } // function stakeFor( // address user, // uint amount, // bytes data // ) // public // pre_cond(isStakingFeed[user]) // { // OperatorStaking.stakeFor(user, amount, data); // } // AGGREGATION /// @dev Only Owner; Same sized input arrays /// @dev Updates price of asset relative to QUOTE_ASSET /** Ex: * Let QUOTE_ASSET == MLN (base units), let asset == EUR-T, * let Value of 1 EUR-T := 1 EUR == 0.080456789 MLN, hence price 0.080456789 MLN / EUR-T * and let EUR-T decimals == 8. * Input would be: information[EUR-T].price = 8045678 [MLN/ (EUR-T * 10**8)] */ /// @param ofAssets list of asset addresses function collectAndUpdate(address[] ofAssets) public auth pre_cond(updatesAreAllowed) { uint[] memory newPrices = pricesToCommit(ofAssets); priceHistory.push( HistoricalPrices({assets: ofAssets, prices: newPrices, timestamp: block.timestamp}) ); _updatePrices(ofAssets, newPrices); } function pricesToCommit(address[] ofAssets) view returns (uint[]) { address[] memory operators = getOperators(); uint[] memory newPrices = new uint[](ofAssets.length); for (uint i = 0; i < ofAssets.length; i++) { uint[] memory assetPrices = new uint[](operators.length); for (uint j = 0; j < operators.length; j++) { SimplePriceFeed feed = SimplePriceFeed(operators[j]); var (price, timestamp) = feed.assetsToPrices(ofAssets[i]); if (now > add(timestamp, VALIDITY)) { continue; // leaves a zero in the array (dealt with later) } assetPrices[j] = price; } newPrices[i] = medianize(assetPrices); } return newPrices; } /// @dev from MakerDao medianizer contract function medianize(uint[] unsorted) view returns (uint) { uint numValidEntries; for (uint i = 0; i < unsorted.length; i++) { if (unsorted[i] != 0) { numValidEntries++; } } if (numValidEntries < minimumPriceCount) { revert(); } uint counter; uint[] memory out = new uint[](numValidEntries); for (uint j = 0; j < unsorted.length; j++) { uint item = unsorted[j]; if (item != 0) { // skip zero (invalid) entries if (counter == 0 || item >= out[counter - 1]) { out[counter] = item; // item is larger than last in array (we are home) } else { uint k = 0; while (item >= out[k]) { k++; // get to where element belongs (between smaller and larger items) } for (uint m = counter; m > k; m--) { out[m] = out[m - 1]; // bump larger elements rightward to leave slot } out[k] = item; } counter++; } } uint value; if (counter % 2 == 0) { uint value1 = uint(out[(counter / 2) - 1]); uint value2 = uint(out[(counter / 2)]); value = add(value1, value2) / 2; } else { value = out[(counter - 1) / 2]; } return value; } function setMinimumPriceCount(uint newCount) auth { minimumPriceCount = newCount; } function enableUpdates() auth { updatesAreAllowed = true; } function disableUpdates() auth { updatesAreAllowed = false; } // PUBLIC VIEW METHODS // FEED INFORMATION function getQuoteAsset() view returns (address) { return QUOTE_ASSET; } function getInterval() view returns (uint) { return INTERVAL; } function getValidity() view returns (uint) { return VALIDITY; } function getLastUpdateId() view returns (uint) { return updateId; } // PRICES /// @notice Whether price of asset has been updated less than VALIDITY seconds ago /// @param ofAsset Asset in registrar /// @return isRecent Price information ofAsset is recent function hasRecentPrice(address ofAsset) view pre_cond(assetIsRegistered(ofAsset)) returns (bool isRecent) { var ( , timestamp) = getPrice(ofAsset); return (sub(now, timestamp) <= VALIDITY); } /// @notice Whether prices of assets have been updated less than VALIDITY seconds ago /// @param ofAssets All assets in registrar /// @return isRecent Price information ofAssets array is recent function hasRecentPrices(address[] ofAssets) view returns (bool areRecent) { for (uint i; i < ofAssets.length; i++) { if (!hasRecentPrice(ofAssets[i])) { return false; } } return true; } function getPriceInfo(address ofAsset) view returns (bool isRecent, uint price, uint assetDecimals) { isRecent = hasRecentPrice(ofAsset); (price, ) = getPrice(ofAsset); assetDecimals = getDecimals(ofAsset); } /** @notice Gets inverted price of an asset @dev Asset has been initialised and its price is non-zero @dev Existing price ofAssets quoted in QUOTE_ASSET (convention) @param ofAsset Asset for which inverted price should be return @return { "isRecent": "Whether the price is fresh, given VALIDITY interval", "invertedPrice": "Price based (instead of quoted) against QUOTE_ASSET", "assetDecimals": "Decimal places for this asset" } */ function getInvertedPriceInfo(address ofAsset) view returns (bool isRecent, uint invertedPrice, uint assetDecimals) { uint inputPrice; // inputPrice quoted in QUOTE_ASSET and multiplied by 10 ** assetDecimal (isRecent, inputPrice, assetDecimals) = getPriceInfo(ofAsset); // outputPrice based in QUOTE_ASSET and multiplied by 10 ** quoteDecimal uint quoteDecimals = getDecimals(QUOTE_ASSET); return ( isRecent, mul(10 ** uint(quoteDecimals), 10 ** uint(assetDecimals)) / inputPrice, quoteDecimals // TODO: check on this; shouldn't it be assetDecimals? ); } /** @notice Gets reference price of an asset pair @dev One of the address is equal to quote asset @dev either ofBase == QUOTE_ASSET or ofQuote == QUOTE_ASSET @param ofBase Address of base asset @param ofQuote Address of quote asset @return { "isRecent": "Whether the price is fresh, given VALIDITY interval", "referencePrice": "Reference price", "decimal": "Decimal places for this asset" } */ function getReferencePriceInfo(address ofBase, address ofQuote) view returns (bool isRecent, uint referencePrice, uint decimal) { if (getQuoteAsset() == ofQuote) { (isRecent, referencePrice, decimal) = getPriceInfo(ofBase); } else if (getQuoteAsset() == ofBase) { (isRecent, referencePrice, decimal) = getInvertedPriceInfo(ofQuote); } else { revert(); // no suitable reference price available } } /// @notice Gets price of Order /// @param sellAsset Address of the asset to be sold /// @param buyAsset Address of the asset to be bought /// @param sellQuantity Quantity in base units being sold of sellAsset /// @param buyQuantity Quantity in base units being bought of buyAsset /// @return orderPrice Price as determined by an order function getOrderPriceInfo( address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (uint orderPrice) { return mul(buyQuantity, 10 ** uint(getDecimals(sellAsset))) / sellQuantity; } /// @notice Checks whether data exists for a given asset pair /// @dev Prices are only upated against QUOTE_ASSET /// @param sellAsset Asset for which check to be done if data exists /// @param buyAsset Asset for which check to be done if data exists /// @return Whether assets exist for given asset pair function existsPriceOnAssetPair(address sellAsset, address buyAsset) view returns (bool isExistent) { return hasRecentPrice(sellAsset) && // Is tradable asset (TODO cleaner) and datafeed delivering data hasRecentPrice(buyAsset) && // Is tradable asset (TODO cleaner) and datafeed delivering data (buyAsset == QUOTE_ASSET || sellAsset == QUOTE_ASSET) && // One asset must be QUOTE_ASSET (buyAsset != QUOTE_ASSET || sellAsset != QUOTE_ASSET); // Pair must consists of diffrent assets } /// @return Sparse array of addresses of owned pricefeeds function getPriceFeedsByOwner(address _owner) view returns(address[]) { address[] memory ofPriceFeeds = new address[](numStakers); if (numStakers == 0) return ofPriceFeeds; uint current = stakeNodes[0].next; for (uint i; i < numStakers; i++) { StakingPriceFeed stakingFeed = StakingPriceFeed(stakeNodes[current].data.staker); if (stakingFeed.owner() == _owner) { ofPriceFeeds[i] = address(stakingFeed); } current = stakeNodes[current].next; } return ofPriceFeeds; } function getHistoryLength() returns (uint) { return priceHistory.length; } function getHistoryAt(uint id) returns (address[], uint[], uint) { address[] memory assets = priceHistory[id].assets; uint[] memory prices = priceHistory[id].prices; uint timestamp = priceHistory[id].timestamp; return (assets, prices, timestamp); } } interface VersionInterface { // EVENTS event FundUpdated(uint id); // PUBLIC METHODS function shutDown() external; function setupFund( bytes32 ofFundName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address[] ofExchanges, address[] ofDefaultAssets, uint8 v, bytes32 r, bytes32 s ); function shutDownFund(address ofFund); // PUBLIC VIEW METHODS function getNativeAsset() view returns (address); function getFundById(uint withId) view returns (address); function getLastFundId() view returns (uint); function getFundByManager(address ofManager) view returns (address); function termsAndConditionsAreSigned(uint8 v, bytes32 r, bytes32 s) view returns (bool signed); } contract Version is DBC, Owned, VersionInterface { // FIELDS bytes32 public constant TERMS_AND_CONDITIONS = 0xAA9C907B0D6B4890E7225C09CBC16A01CB97288840201AA7CDCB27F4ED7BF159; // Hashed terms and conditions as displayed on IPFS, decoded from base 58 // Constructor fields string public VERSION_NUMBER; // SemVer of Melon protocol version address public MELON_ASSET; // Address of Melon asset contract address public NATIVE_ASSET; // Address of Fixed quote asset address public GOVERNANCE; // Address of Melon protocol governance contract address public CANONICAL_PRICEFEED; // Address of the canonical pricefeed // Methods fields bool public isShutDown; // Governance feature, if yes than setupFund gets blocked and shutDownFund gets opened address public COMPLIANCE; // restrict to Competition compliance module for this version address[] public listOfFunds; // A complete list of fund addresses created using this version mapping (address => address) public managerToFunds; // Links manager address to fund address created using this version // EVENTS event FundUpdated(address ofFund); // METHODS // CONSTRUCTOR /// @param versionNumber SemVer of Melon protocol version /// @param ofGovernance Address of Melon governance contract /// @param ofMelonAsset Address of Melon asset contract function Version( string versionNumber, address ofGovernance, address ofMelonAsset, address ofNativeAsset, address ofCanonicalPriceFeed, address ofCompetitionCompliance ) { VERSION_NUMBER = versionNumber; GOVERNANCE = ofGovernance; MELON_ASSET = ofMelonAsset; NATIVE_ASSET = ofNativeAsset; CANONICAL_PRICEFEED = ofCanonicalPriceFeed; COMPLIANCE = ofCompetitionCompliance; } // EXTERNAL METHODS function shutDown() external pre_cond(msg.sender == GOVERNANCE) { isShutDown = true; } // PUBLIC METHODS /// @param ofFundName human-readable descriptive name (not necessarily unique) /// @param ofQuoteAsset Asset against which performance fee is measured against /// @param ofManagementFee A time based fee, given in a number which is divided by 10 ** 15 /// @param ofPerformanceFee A time performance based fee, performance relative to ofQuoteAsset, given in a number which is divided by 10 ** 15 /// @param ofCompliance Address of participation module /// @param ofRiskMgmt Address of risk management module /// @param ofExchanges Addresses of exchange on which this fund can trade /// @param ofDefaultAssets Enable invest/redeem with these assets (quote asset already enabled) /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s function setupFund( bytes32 ofFundName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address[] ofExchanges, address[] ofDefaultAssets, uint8 v, bytes32 r, bytes32 s ) { require(!isShutDown); require(termsAndConditionsAreSigned(v, r, s)); require(CompetitionCompliance(COMPLIANCE).isCompetitionAllowed(msg.sender)); require(managerToFunds[msg.sender] == address(0)); // Add limitation for simpler migration process of shutting down and setting up fund address[] memory melonAsDefaultAsset = new address[](1); melonAsDefaultAsset[0] = MELON_ASSET; // Melon asset should be in default assets address ofFund = new Fund( msg.sender, ofFundName, NATIVE_ASSET, 0, 0, COMPLIANCE, ofRiskMgmt, CANONICAL_PRICEFEED, ofExchanges, melonAsDefaultAsset ); listOfFunds.push(ofFund); managerToFunds[msg.sender] = ofFund; emit FundUpdated(ofFund); } /// @dev Dereference Fund and shut it down /// @param ofFund Address of the fund to be shut down function shutDownFund(address ofFund) pre_cond(isShutDown || managerToFunds[msg.sender] == ofFund) { Fund fund = Fund(ofFund); delete managerToFunds[msg.sender]; fund.shutDown(); emit FundUpdated(ofFund); } // PUBLIC VIEW METHODS /// @dev Proof that terms and conditions have been read and understood /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s /// @return signed Whether or not terms and conditions have been read and understood function termsAndConditionsAreSigned(uint8 v, bytes32 r, bytes32 s) view returns (bool signed) { return ecrecover( // Parity does prepend \x19Ethereum Signed Message:\n{len(message)} before signing. // Signature order has also been changed in 1.6.7 and upcoming 1.7.x, // it will return rsv (same as geth; where v is [27, 28]). // Note that if you are using ecrecover, v will be either "00" or "01". // As a result, in order to use this value, you will have to parse it to an // integer and then add 27. This will result in either a 27 or a 28. // https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsign keccak256("\x19Ethereum Signed Message:\n32", TERMS_AND_CONDITIONS), v, r, s ) == msg.sender; // Has sender signed TERMS_AND_CONDITIONS } function getNativeAsset() view returns (address) { return NATIVE_ASSET; } function getFundById(uint withId) view returns (address) { return listOfFunds[withId]; } function getLastFundId() view returns (uint) { return listOfFunds.length - 1; } function getFundByManager(address ofManager) view returns (address) { return managerToFunds[ofManager]; } }
Register an exchange information entry Pre: Only registrar owner should be able to register Post: Address ofExchange is registered ofExchange Address of the exchange ofExchangeAdapter Address of exchange adapter for this exchange inputTakesCustody Whether this exchange takes custody of tokens before trading inputFunctionSignatures Function signatures for whitelisted exchange functions
function registerExchange( address ofExchange, address ofExchangeAdapter, bool inputTakesCustody, bytes4[] inputFunctionSignatures ) auth pre_cond(!exchangeInformation[ofExchange].exists) { exchangeInformation[ofExchange].exists = true; registeredExchanges.push(ofExchange); updateExchange( ofExchange, ofExchangeAdapter, inputTakesCustody, inputFunctionSignatures ); assert(exchangeInformation[ofExchange].exists); }
196,288
// SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.7.0; import "@openzeppelin/contracts/token/ERC777/ERC777.sol"; import "./interfaces/IArbToken.sol"; contract L2Land is ERC777, IArbToken { address public l2Gateway; address public override l1Address; modifier onlyGateway { require(msg.sender == l2Gateway, "ONLY_GATEWAY"); _; } constructor( address _l2Gateway, address _l1Counterpart ) public ERC777("Land", "LAND", new address[](0)) { require(_l2Gateway != address(0), "INVALID_GATEWAY"); require(l2Gateway == address(0), "ALREADY_INIT"); l2Gateway = _l2Gateway; l1Address = _l1Counterpart; } /** * @notice Mint tokens on L2. Callable path is L1Gateway depositToken (which handles L1 escrow), which triggers L2Gateway, which calls this * @param account recipient of tokens * @param amount amount of tokens minted */ function bridgeMint(address account, uint256 amount) external virtual override onlyGateway { bytes calldata data; _mint(account, amount, data, ''); } /** * @notice Burn tokens on L2. * @dev only the token bridge can call this * @param account owner of tokens * @param amount amount of tokens burnt */ function bridgeBurn(address account, uint256 amount) external virtual override onlyGateway { bytes calldata data; _burn(account, amount, data, ''); } }
Burn tokens on L2. only the token bridge can call this account owner of tokens amount amount of tokens burnt/
function bridgeBurn(address account, uint256 amount) external virtual override onlyGateway { bytes calldata data; _burn(account, amount, data, ''); }
15,868,759
./partial_match/3/0xc5caAcB9F860d72201318F8519A8770713651927/sources/YZYVault.sol
Update Staker's Treasury Available Rewards/ For All Stakers Get Staker Update Staker's Treasury available reward Update Staker's Treasury pending reward
function _updateTreasuryAvailableRewards() internal { for (uint256 i = 0; i < _stakerList.length; i++) { address staker = _stakerList[i]; _stakers[staker].treasuryAvailableReward.add( _stakers[staker].treasuryPendingReward ); _stakers[staker].treasuryPendingReward = 0; } }
5,290,273
./full_match/5/0x7cCa8f6fE3757f67764635F30EfD4711F83220a8/sources/contracts/Equb.sol
get the equb balance Call the investInCampaign function on the instance of the contract
function investInStartup( address payable _startup, address payable equbAddress ) public { uint poolIndex = getPoolIndex(equbAddress); uint amount = pools[poolIndex].equbBalance; _startup.transfer(amount); pools[poolIndex].equbBalance = 0; }
1,937,748
./full_match/1/0x517a197ad807703D99d919afcd720B5F4a2AA9fC/sources/contracts/uniswapv2/libraries/UniswapV2Library.sol
fetches and sorts the reserves for a pair
function getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(IUniswapV2Factory(factory).getPair(tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); }
16,394,010
./full_match/1/0x0C58579eCeDa5bFb87448da1F8bD6c99175640eb/sources/contracts/AdapterHelper.sol
Tells TokenProfit contract to deposit funds into LiquidNFTs pool/
function _depositLiquidNFTsWrapper( ILiquidNFTsPool _pool, uint256 _amount ) internal { tokenProfit.executeAdapterRequest( LIQUID_NFT_ROUTER_ADDRESS, abi.encodeWithSelector( ILiquidNFTsRouter.depositFunds.selector, _amount, _pool ) ); }
9,701,634
./full_match/80001/0xf446930D66E7a32b013A602295a919772B20AB41/sources/contracts/PrizeSavingToken.sol
token Id token Id => time result jackpost Token Id => index result consolation Token Id => index
{ using SafeERC20 for IERC20; using TWStrings for uint256; uint256 private nextTokenIdToMint_; mapping(address => bool) public isAdminListed; mapping(uint256 => uint256) public statusDrawed; mapping(uint256 => uint256) public timeDrawed; mapping(uint256 => uint256) public resultJackpot; mapping(uint256 => uint256) public resultConsolation; uint256 public currentRaffleId = 0; mapping(uint256 => uint256) public totalSupply; constructor(string memory _name, string memory _symbol) ERC1155(_name, _symbol) pragma solidity ^0.8.2; { _setupOwner(msg.sender); } modifier onlyAdmin() { require(isAdminListed[msg.sender], "Ownable: caller is not the admin"); _; } function setAdmin(address admin_) public onlyOwner { require(admin_ != address(0), "SetAdmin: Zero address owner"); isAdminListed[admin_] = true; } function removeAdmin(address admin_) public onlyOwner { require(admin_ != address(0), "RemoveAdmin: Zero address owner"); isAdminListed[admin_] = false; } function setPayoutTokenAddress(address _payoutTokenAddress) external onlyAdmin { payoutTokenAddress = _payoutTokenAddress; } function mintTicket( address _to, uint256 _amount, uint256 _id ) external onlyAdmin { currentRaffleId = _id; _mint(_to, _id, _amount, ""); } function batchTransferTickets( uint256 _tokenId, uint256 _time, address[] memory _receivers, uint256[] memory _amounts ) external onlyAdmin { require( _receivers.length == _amounts.length, "Invalid leng receivers and amounts" ); for (uint256 index = 0; index < _receivers.length; index++) { safeTransferFrom( msg.sender, _receivers[index], _tokenId, _amounts[index], "" ); } statusDrawed[_tokenId] = 1; timeDrawed[_tokenId] = _time; } function batchTransferTickets( uint256 _tokenId, uint256 _time, address[] memory _receivers, uint256[] memory _amounts ) external onlyAdmin { require( _receivers.length == _amounts.length, "Invalid leng receivers and amounts" ); for (uint256 index = 0; index < _receivers.length; index++) { safeTransferFrom( msg.sender, _receivers[index], _tokenId, _amounts[index], "" ); } statusDrawed[_tokenId] = 1; timeDrawed[_tokenId] = _time; } function drawRaffle( uint256 _tokenId, uint256 _time, uint256 _totalTicket ) external onlyAdmin { require(statusDrawed[_tokenId] == 1, "The round already drawed"); require(timeDrawed[_tokenId] == _time, "Invalid time and token id"); resultJackpot[_tokenId] = _random(_totalTicket, _totalTicket); resultConsolation[_tokenId] = _random(5, _totalTicket); statusDrawed[_tokenId] = 2; } function payout( uint256 _tokenId, uint256 _time, address[] memory _receivers, uint256[] memory _amounts ) external onlyAdmin { require(statusDrawed[_tokenId] == 2, "The round already drawed"); require(timeDrawed[_tokenId] == _time, "Invalid time and token id"); require( payoutTokenAddress != address(0), "Payout token address is not set" ); require( _receivers.length == _amounts.length, "Invalid receivers and amounts lenght" ); for (uint256 index = 0; index < _receivers.length; index++) { require( balanceOf[address(_receivers[index])][_tokenId] > 0, "No tickets issued for this draw" ); IERC20(payoutTokenAddress).transfer( address(_receivers[index]), _amounts[index] * 10**18 ); } statusDrawed[_tokenId] = 3; } function payout( uint256 _tokenId, uint256 _time, address[] memory _receivers, uint256[] memory _amounts ) external onlyAdmin { require(statusDrawed[_tokenId] == 2, "The round already drawed"); require(timeDrawed[_tokenId] == _time, "Invalid time and token id"); require( payoutTokenAddress != address(0), "Payout token address is not set" ); require( _receivers.length == _amounts.length, "Invalid receivers and amounts lenght" ); for (uint256 index = 0; index < _receivers.length; index++) { require( balanceOf[address(_receivers[index])][_tokenId] > 0, "No tickets issued for this draw" ); IERC20(payoutTokenAddress).transfer( address(_receivers[index]), _amounts[index] * 10**18 ); } statusDrawed[_tokenId] = 3; } Internal functions function _random(uint256 _modulus, uint256 _index) internal view returns (uint256) { return uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, msg.sender, _index ) ) ) % _modulus; } function _canSetContractURI() internal view override returns (bool) { return msg.sender == owner(); } function _canMint() internal view returns (bool) { return msg.sender == owner(); } function _canSetOwner() internal view override returns (bool) { return msg.sender == owner(); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } View functions function nextTokenIdToMint() public view returns (uint256) { return nextTokenIdToMint_; } }
5,643,755
/** * @title OnboardRouter * @author Team 3301 <[email protected]> * @dev OnboardRouter contract, that allows one individual transaction to onboard a particular subset of users onto * the Sygnum platform, instead of having to initiate X amount of transactions. */ pragma solidity 0.5.12; import "../helpers/interface/IWhitelist.sol"; import "../role/base/Operatorable.sol"; import "../role/interface/IBaseOperators.sol"; import "../role/interface/IRaiseOperators.sol"; import "../role/interface/ITraderOperators.sol"; import "../role/interface/IBlockerOperators.sol"; contract OnboardRouter is Operatorable { IWhitelist internal whitelistInst; IRaiseOperators internal raiseOperatorsInst; ITraderOperators internal traderOperatorsInst; IBlockerOperators internal blockerOperatorsInst; event WhitelistContractChanged(address indexed caller, address indexed whitelistAddress); event BaseOperatorsContractChanged(address indexed caller, address indexed baseOperatorsAddress); event RaiseOperatorsContractChanged(address indexed caller, address indexed raiseOperatorsAddress); event TraderOperatorsContractChanged(address indexed caller, address indexed traderOperatorsAddress); event BlockerOperatorsContractChanged(address indexed caller, address indexed blockerOperatorsAddress); /** * @dev Initialization instead of constructor, called once. The setOperatorsContract function can be called only by Admin role with * confirmation through the operators contract. * @param _baseOperators BaseOperators contract address. * @param _raiseOperators RaiseOperators contract address. * @param _traderOperators TraderOperators contract address. * @param _blockerOperators BlockerOperators contract address. */ function initialize( address _whitelist, address _baseOperators, address _raiseOperators, address _traderOperators, address _blockerOperators ) public initializer { _setWhitelistContract(_whitelist); _setBaseOperatorsContract(_baseOperators); _setRaiseOperatorsContract(_raiseOperators); _setTraderOperatorsContract(_traderOperators); _setBlockerOperatorsContract(_blockerOperators); } /** * @dev Admin can give '_account' address system privileges, whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be given system privileges. * @param _whitelist Whitelist contract address. */ function onboardSystem(address _account, address _whitelist) public onlyAdmin { _toggleWhitelist(_account, _whitelist, true); operatorsInst.addSystem(_account); } /** * @dev Admin can revoke '_account' address system privileges, de-whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be revoked system privileges. * @param _whitelist Whitelist contract address. */ function deboardSystem(address _account, address _whitelist) public onlyAdmin { _toggleWhitelist(_account, _whitelist, false); operatorsInst.removeSystem(_account); } /** * @dev Admin can give '_account' address super admin privileges, whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be given super admin privileges. * @param _whitelist Whitelist contract address. */ function onboardSuperAdmin(address _account, address _whitelist) public onlyAdmin { _toggleWhitelist(_account, _whitelist, true); operatorsInst.addOperatorAndAdmin(_account); traderOperatorsInst.addTrader(_account); } /** * @dev Admin can revoke '_account' address super admin privileges, de-whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be revoked super admin privileges. * @param _whitelist Whitelist contract address. */ function deboardSuperAdmin(address _account, address _whitelist) public onlyAdmin { _toggleWhitelist(_account, _whitelist, false); operatorsInst.removeOperatorAndAdmin(_account); traderOperatorsInst.removeTrader(_account); } /** * @dev Operator or System can give '_account' address investor privileges, whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be given investor privileges. * @param _whitelist Whitelist contract address. */ function onboardInvestor(address _account, address _whitelist) public onlyOperatorOrSystem { _toggleWhitelist(_account, _whitelist, true); raiseOperatorsInst.addInvestor(_account); } /** * @dev Operator or System can revoke '_account' address investor privileges, de-whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be revoked investor privileges. * @param _whitelist Whitelist contract address. */ function deboardInvestor(address _account, address _whitelist) public onlyOperatorOrSystem { _toggleWhitelist(_account, _whitelist, false); raiseOperatorsInst.removeInvestor(_account); } /** * @dev Admin can give '_account' address trader privileges, whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be given trader privileges. * @param _whitelist Whitelist contract address. */ function onboardTrader(address _account, address _whitelist) public onlyAdmin { _toggleWhitelist(_account, _whitelist, true); traderOperatorsInst.addTrader(_account); } /** * @dev Admin can revoke '_account' address trader privileges, de-whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be revoked trader privileges. * @param _whitelist Whitelist contract address. */ function deboardTrader(address _account, address _whitelist) public onlyAdmin { _toggleWhitelist(_account, _whitelist, false); traderOperatorsInst.removeTrader(_account); } /** * @dev Admin can give '_account' address blocker privileges, whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be given blocker privileges. * @param _whitelist Whitelist contract address. */ function onboardBlocker(address _account, address _whitelist) public onlyAdmin { _toggleWhitelist(_account, _whitelist, true); blockerOperatorsInst.addBlocker(_account); } /** * @dev Admin can revoke '_account' address blocker privileges, de-whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be revoked blocker privileges. * @param _whitelist Whitelist contract address. */ function deboardBlocker(address _account, address _whitelist) public onlyAdmin { _toggleWhitelist(_account, _whitelist, false); blockerOperatorsInst.removeBlocker(_account); } /** * @dev Admin can change admin '_account' address to only trader privileges, whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be given trader privileges. * @param _whitelist Whitelist contract address. */ function changeAdminToTrader(address _account, address _whitelist) public onlyAdmin { _toggleWhitelist(_account, _whitelist, true); operatorsInst.removeAdmin(_account); traderOperatorsInst.addTrader(_account); } /** * @dev Admin can change admin '_account' address to superAdmin privileges, whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be given trader privileges. * @param _whitelist Whitelist contract address. */ function changeAdminToSuperAdmin(address _account, address _whitelist) public onlyAdmin { require(isAdmin(_account), "OnboardRouter: selected account does not have admin privileges"); _toggleWhitelist(_account, _whitelist, true); operatorsInst.addOperator(_account); traderOperatorsInst.addTrader(_account); } /** * @dev Admin can change operator '_account' address to trader privileges, whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be given trader privileges. * @param _whitelist Whitelist contract address. */ function changeOperatorToTrader(address _account, address _whitelist) public onlyAdmin { _toggleWhitelist(_account, _whitelist, true); operatorsInst.removeOperator(_account); traderOperatorsInst.addTrader(_account); } /** * @dev Admin can change operator '_account' address to superAdmin privileges, whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be given trader privileges. * @param _whitelist Whitelist contract address. */ function changeOperatorToSuperAdmin(address _account, address _whitelist) public onlyAdmin { require(isOperator(_account), "OnboardRouter: selected account does not have operator privileges"); _toggleWhitelist(_account, _whitelist, true); operatorsInst.addAdmin(_account); traderOperatorsInst.addTrader(_account); } /** * @dev Admin can change trader '_account' address to admin privileges, de-whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be given trader privileges. * @param _whitelist Whitelist contract address. */ function changeTraderToAdmin(address _account, address _whitelist) public onlyAdmin { _toggleWhitelist(_account, _whitelist, false); operatorsInst.addAdmin(_account); traderOperatorsInst.removeTrader(_account); } /** * @dev Admin can change trader '_account' address to operator privileges, whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be given trader privileges. * @param _whitelist Whitelist contract address. */ function changeTraderToOperator(address _account, address _whitelist) public onlyAdmin { _toggleWhitelist(_account, _whitelist, false); operatorsInst.addOperator(_account); traderOperatorsInst.removeTrader(_account); } /** * @dev Admin can change superadmin '_account' address to admin privileges, de-whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be given trader privileges. * @param _whitelist Whitelist contract address. */ function changeSuperAdminToAdmin(address _account, address _whitelist) public onlyAdmin { require(isAdmin(_account), "OnboardRouter: account is not admin"); _toggleWhitelist(_account, _whitelist, false); operatorsInst.removeOperator(_account); traderOperatorsInst.removeTrader(_account); } /** * @dev Admin can change superadmin '_account' address to operator privileges, de-whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. * @param _account address that should be given trader privileges. * @param _whitelist Whitelist contract address. */ function changeSuperAdminToOperator(address _account, address _whitelist) public onlyAdmin { require(isAdmin(_account), "OnboardRouter: account is not admin"); _toggleWhitelist(_account, _whitelist, false); operatorsInst.removeAdmin(_account); traderOperatorsInst.removeTrader(_account); } /** * @dev Change address of Whitelist contract. * @param _whitelist Whitelist contract address. */ function changeWhitelistContract(address _whitelist) public onlyAdmin { _setWhitelistContract(_whitelist); } /** * @dev Change address of BaseOperators contract. * @param _baseOperators BaseOperators contract address. */ function changeBaseOperatorsContract(address _baseOperators) public onlyAdmin { _setBaseOperatorsContract(_baseOperators); } /** * @dev Change address of RaiseOperators contract. * @param _raiseOperators RaiseOperators contract address. */ function changeRaiseOperatorsContract(address _raiseOperators) public onlyAdmin { _setRaiseOperatorsContract(_raiseOperators); } /** * @dev Change address of TraderOperators contract. * @param _traderOperators TraderOperators contract address. */ function changeTraderOperatorsContract(address _traderOperators) public onlyAdmin { _setTraderOperatorsContract(_traderOperators); } /** * @dev Change address of BlockerOperators contract. * @param _blockerOperators BlockerOperators contract address. */ function changeBlockerOperatorsContract(address _blockerOperators) public onlyAdmin { _setBlockerOperatorsContract(_blockerOperators); } /** * @return Stored address of the Whitelist contract. */ function getWhitelistContract() public view returns (address) { return address(whitelistInst); } /** * @return Stored address of the BaseOperators contract. */ function getBaseOperatorsContract() public view returns (address) { return address(operatorsInst); } /** * @return Stored address of the RaiseOperators contract. */ function getRaiseOperatorsContract() public view returns (address) { return address(raiseOperatorsInst); } /** * @return Stored address of the TraderOperators contract. */ function getTraderOperatorsContract() public view returns (address) { return address(traderOperatorsInst); } /** * @return Stored address of the BlockerOperators contract. */ function getBlockerOperatorsContract() public view returns (address) { return address(blockerOperatorsInst); } /** INTERNAL FUNCTIONS */ function _toggleWhitelist( address _account, address _whitelist, bool _toggle ) internal { whitelistInst.toggleWhitelist(_account, _toggle); if (_whitelist != address(0)) { _toggleSecondaryWhitelist(_account, _whitelist, _toggle); // non-default } } function _toggleSecondaryWhitelist( address _account, address _whitelist, bool _toggle ) internal { IWhitelist(_whitelist).toggleWhitelist(_account, _toggle); } function _setWhitelistContract(address _whitelist) internal { require(_whitelist != address(0), "OnboardRouter: address of new whitelist contract cannot be zero"); whitelistInst = IWhitelist(_whitelist); emit WhitelistContractChanged(msg.sender, _whitelist); } function _setBaseOperatorsContract(address _baseOperators) internal { require(_baseOperators != address(0), "OnboardRouter: address of new baseOperators contract cannot be zero"); operatorsInst = IBaseOperators(_baseOperators); emit BaseOperatorsContractChanged(msg.sender, _baseOperators); } function _setRaiseOperatorsContract(address _raiseOperators) internal { require(_raiseOperators != address(0), "OnboardRouter: address of new raiseOperators contract cannot be zero"); raiseOperatorsInst = IRaiseOperators(_raiseOperators); emit RaiseOperatorsContractChanged(msg.sender, _raiseOperators); } function _setTraderOperatorsContract(address _traderOperators) internal { require( _traderOperators != address(0), "OnboardRouter: address of new traderOperators contract cannot be zero" ); traderOperatorsInst = ITraderOperators(_traderOperators); emit TraderOperatorsContractChanged(msg.sender, _traderOperators); } function _setBlockerOperatorsContract(address _blockerOperators) internal { require( _blockerOperators != address(0), "OnboardRouter: address of new blockerOperators contract cannot be zero" ); blockerOperatorsInst = IBlockerOperators(_blockerOperators); emit BlockerOperatorsContractChanged(msg.sender, _blockerOperators); } }
Admin can give '_account' address blocker privileges, whitelist them on the shared whitelist contract, and the passed in whitelist address i.e. Equity Token, or the default whitelist. _account address that should be given blocker privileges. _whitelist Whitelist contract address./
function onboardBlocker(address _account, address _whitelist) public onlyAdmin { _toggleWhitelist(_account, _whitelist, true); blockerOperatorsInst.addBlocker(_account); }
5,353,042
// File: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/master/contracts/utils/math/SafeMathUpgradeable.sol // 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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/master/contracts/utils/AddressUpgradeable.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); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/master/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library 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"); } } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/master/contracts/token/ERC20/IERC20Upgradeable.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); } // File: DailyVesting.sol pragma solidity 0.8; pragma experimental ABIEncoderV2; contract DailyVesting { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; struct VestingPeriod { uint128 vestingDays; uint128 tokensPerDay; } struct VestingClaimInfo { uint128 lastClaim; uint128 daysClaimed; } //token to be distributed IERC20Upgradeable public token; //handles setup address public setupAdmin; //UTC timestamp from which first vesting period begins (i.e. tokens will first be released 30 days after this time) uint256 public startTime; //total token obligations from all unpaid vesting amounts uint256 public totalObligations; //keeps track of contract state bool public setupComplete; // how long to wait before unlocking admin access uint256 public adminAccessDelay; //list of all beneficiaries address[] public beneficiaries; //amount of tokens to be received by each beneficiary mapping(address => VestingPeriod) public vestingPeriods; mapping(address => VestingClaimInfo) public claimInfo; //tracks if addresses have already been added as beneficiaries or not mapping(address => bool) public beneficiaryAdded; event SetupCompleted(); event BeneficiaryAdded(address indexed user, uint256 totalAmountToClaim); event TokensClaimed(address indexed user, uint256 amount); modifier setupOnly() { require(!setupComplete, "setup already completed"); _; } modifier claimAllowed() { require(setupComplete, "setup ongoing"); _; } modifier onlyAdmin() { require(msg.sender == setupAdmin, "not admin"); _; } modifier whenAdminAccessAvailable() { uint256 _startTime = startTime; require(_startTime < block.timestamp && block.timestamp - _startTime > adminAccessDelay, "admin access is not active"); _; } constructor( IERC20Upgradeable _token, address _owner, uint256 _startTime, uint256 _adminAccessDelay ) public { adminAccessDelay = _adminAccessDelay; token = _token; setupAdmin = msg.sender; startTime = _startTime == 0 ? block.timestamp : _startTime; } // adds a list of beneficiaries function addBeneficiaries(address[] memory _beneficiaries, VestingPeriod[] memory _vestingPeriods) external onlyAdmin setupOnly { _setBeneficiaries(_beneficiaries, _vestingPeriods); } function tokensToClaim(address _beneficiary) public view returns(uint256) { (uint256 tokensAmount,) = _tokensToClaim(_beneficiary, claimInfo[_beneficiary]); return tokensAmount; } /** @dev This function returns tokensAmount available to claim. Calculates it based on several vesting periods if applicable. */ function _tokensToClaim(address _beneficiary, VestingClaimInfo memory claim) private view returns(uint256 tokensAmount, uint256 daysClaimed) { uint256 lastClaim = claim.lastClaim == 0 ? startTime : claim.lastClaim; if (lastClaim > block.timestamp) { // last claim was in the future (means startTime was set in the future) return (0, 0); } uint256 daysElapsed = (block.timestamp - lastClaim) / 1 days; VestingPeriod memory vestingPeriod = vestingPeriods[_beneficiary]; uint256 daysInPeriodToClaim = vestingPeriod.vestingDays - claim.daysClaimed; if (daysInPeriodToClaim > daysElapsed) { daysInPeriodToClaim = daysElapsed; } tokensAmount = tokensAmount.add( uint256(vestingPeriod.tokensPerDay).mul(daysInPeriodToClaim) ); daysElapsed -= daysInPeriodToClaim; daysClaimed += daysInPeriodToClaim; } // claims vested tokens for a given beneficiary function claimFor(address _beneficiary) external claimAllowed { _processClaim(_beneficiary); } // convenience function for beneficiaries to call to claim all of their vested tokens function claimForSelf() external claimAllowed { _processClaim(msg.sender); } // claims vested tokens for all beneficiaries function claimForAll() external claimAllowed { for (uint256 i = 0; i < beneficiaries.length; i++) { _processClaim(beneficiaries[i]); } } // complete setup once all obligations are met, to remove the ability to // reclaim tokens until vesting is complete, and allow claims to start function endSetup() external onlyAdmin setupOnly { uint256 tokenBalance = token.balanceOf(address(this)); require(tokenBalance >= totalObligations, "obligations not yet met"); setupComplete = true; setupAdmin = address(0); emit SetupCompleted(); } // reclaim tokens if necessary prior to finishing setup. otherwise reclaim any // extra tokens after the end of vesting function reclaimTokens() external onlyAdmin setupOnly { token.transfer(setupAdmin, token.balanceOf(address(this))); } function emergencyReclaimTokens() external onlyAdmin whenAdminAccessAvailable { token.transfer(setupAdmin, token.balanceOf(address(this))); } function emergencyOverrideBenefeciaries(address[] memory _beneficiaries, VestingPeriod[] memory _vestingPeriods) external onlyAdmin whenAdminAccessAvailable { for (uint256 i = 0; i < _beneficiaries.length; i++) { beneficiaryAdded[_beneficiaries[i]] = false; } _setBeneficiaries(_beneficiaries, _vestingPeriods); } // Calculates the claimable tokens of a beneficiary and sends them. function _processClaim(address _beneficiary) internal { VestingClaimInfo memory claim = claimInfo[_beneficiary]; (uint256 amountToClaim, uint256 daysClaimed) = _tokensToClaim(_beneficiary, claim); if (amountToClaim == 0) { return; } claim.daysClaimed += uint128(daysClaimed); claim.lastClaim = uint128(block.timestamp); claimInfo[_beneficiary] = claim; _sendTokens(_beneficiary, amountToClaim); emit TokensClaimed(_beneficiary, amountToClaim); } // send tokens to beneficiary and remove obligation function _sendTokens(address _beneficiary, uint256 _amountToSend) internal { totalObligations -= _amountToSend; token.transfer(_beneficiary, _amountToSend); } function _setBeneficiaries(address[] memory _beneficiaries, VestingPeriod[] memory _vestingPeriods) private { require(_beneficiaries.length == _vestingPeriods.length, "input length mismatch"); uint256 _totalObligations; for (uint256 i = 0; i < _beneficiaries.length; i++) { address beneficiary = _beneficiaries[i]; require(!beneficiaryAdded[beneficiary], "beneficiary already added"); beneficiaryAdded[beneficiary] = true; uint256 amountToClaim; VestingPeriod memory period = _vestingPeriods[i]; amountToClaim = amountToClaim.add( uint256(period.vestingDays).mul( uint256(period.tokensPerDay) ) ); vestingPeriods[beneficiary] = period; beneficiaries.push(beneficiary); _totalObligations = _totalObligations.add(amountToClaim); emit BeneficiaryAdded(beneficiary, amountToClaim); } totalObligations = totalObligations.add(_totalObligations); token.safeTransferFrom(msg.sender, address(this), _totalObligations); } }
complete setup once all obligations are met, to remove the ability to reclaim tokens until vesting is complete, and allow claims to start
function endSetup() external onlyAdmin setupOnly { uint256 tokenBalance = token.balanceOf(address(this)); require(tokenBalance >= totalObligations, "obligations not yet met"); setupComplete = true; setupAdmin = address(0); emit SetupCompleted(); }
12,940,923
./full_match/1/0xE5fED113E1969D76c3268f2244EE7b5F3e94a12a/sources/contracts/SwaposToken.sol
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "SWP::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SWP::delegateBySig: invalid nonce"); require(now <= expiry, "SWP::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
16,391,877
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import './openzeppelin-solidity/contracts/SafeMath.sol'; //Interfaces import './interfaces/IExternalStorage.sol'; //Inheritance import './interfaces/IUsers.sol'; import './openzeppelin-solidity/contracts/Ownable.sol'; import './openzeppelin-solidity/contracts/ERC1155/ERC1155.sol'; contract Users is IUsers, ERC1155, Ownable { using SafeMath for uint256; IExternalStorage public externalStorage; bytes32[] public requiredAttributes; mapping (address => uint) public profileIDs; uint public numberOfUsers; constructor(address _externalStorage) Ownable() { externalStorage = IExternalStorage(_externalStorage); } /* ========== VIEWS ========== */ /** * @dev Given the address of a user, returns the user's profile NFT ID. * @notice If the user hasn't minted an NFT profile, the function returns 0. * @param userAddress Address of the user. * @return uint The user's NFT ID. */ function getUser(address userAddress) external view returns (uint) { require(userAddress != address(0), "Users: invalid user address."); return profileIDs[userAddress]; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev Mints an NFT representing the user's profile. * @notice attributeNames must match the required attributes in the same order. * @param attributeNames name of each attribute to initialize. * @param attributeValues value of each attribute to initialize. */ function createProfile(bytes32[] memory attributeNames, bytes[] memory attributeValues) external userDoesntHaveProfile externalStorageIsInitialized { require(profileIDs[msg.sender] == 0, "Users: already have a profile."); require(attributeNames.length == attributeValues.length, "Users: lengths must match."); for (uint i = 0; i < attributeNames.length; i++) { require(requiredAttributes[i] == attributeNames[i], "Users: missing required attribute."); } numberOfUsers = numberOfUsers.add(1); profileIDs[msg.sender] = numberOfUsers; require(externalStorage.initializeValues(numberOfUsers, attributeNames, attributeValues), "Users: error when initializing values."); // Create NFT _mint(msg.sender, numberOfUsers, 1, ""); emit CreatedProfile(msg.sender, numberOfUsers, attributeNames, attributeValues); } /* ========== RESTRICTED FUNCTIONS ========== */ function setExternalStorage(address _externalStorage) external onlyOwner externalStorageIsNotInitialized { require(_externalStorage != address(0), "Users: invalid address for ExternalStorage."); externalStorage = IExternalStorage(_externalStorage); emit SetExternalStorage(_externalStorage); } function addRequiredAttribute(bytes32 _attributeName) external onlyOwner { // Check if attribute already exists for (uint i = 0; i < requiredAttributes.length; i++) { if (requiredAttributes[i] == _attributeName) { return; } } requiredAttributes.push(_attributeName); emit AddedRequiredAttribute(_attributeName); } function removeRequiredAttribute(bytes32 _attributeName) external onlyOwner { uint index; for (index = 0; index < requiredAttributes.length; index++) { if (requiredAttributes[index] == _attributeName) { break; } } if (requiredAttributes.length == 0 || index == requiredAttributes.length) { return; } // Swap with attribute at the end of the array requiredAttributes[index] = requiredAttributes[requiredAttributes.length - 1]; delete requiredAttributes[requiredAttributes.length - 1]; emit RemovedRequiredAttribute(_attributeName); } /* ========== MODIFIERS ========== */ modifier userDoesntHaveProfile() { require(profileIDs[msg.sender] == 0, "Users: user already has a profile."); _; } modifier externalStorageIsNotInitialized() { require(address(externalStorage) == address(0), "Users: ExternalStorage is already initialized."); _; } modifier externalStorageIsInitialized() { require(address(externalStorage) != address(0), "Users: ExternalStorage is not initialized."); _; } /* ========== EVENTS ========== */ event CreatedProfile(address indexed user, uint profileID, bytes32[] attributeNames, bytes[] attributeValues); event SetExternalStorage(address externalStorage); event AddedRequiredAttribute(bytes32 attributeName); event RemovedRequiredAttribute(bytes32 attributeName); }
Given the address of a user, returns the user's profile NFT ID. If the user hasn't minted an NFT profile, the function returns 0. userAddress Address of the user. return uint The user's NFT ID./
function getUser(address userAddress) external view returns (uint) { require(userAddress != address(0), "Users: invalid user address."); return profileIDs[userAddress]; }
13,053,439
pragma solidity ^0.4.24; contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d short only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d short only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularShort is F3Devents {} contract F4Kings is modularShort { using SafeMath for *; using NameFilter for string; using F3DKeysCalcShort for uint256; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xf626967fA13d841fd74D49dEe9bDd0D0dD6C4394); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== address private admin = msg.sender; address private shareCom = 0x431C4354dB7f2b9aC1d9B2019e925C85C725DA5c; string constant public name = "f4kings"; string constant public symbol = "f4kings"; uint256 private rndExtra_ = 0; // length of the very first ICO uint256 private rndGap_ = 2 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 24 hours; // round timer starts at this uint256 constant private rndInc_ = 20 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be uint256 constant private rndLimit_ = 3; // limit rnd eth purchase //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(22,0); //48% to pot, 18% to aff, 10% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(32,0); //38% to pot, 18% to aff, 10% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(52,0); //18% to pot, 18% to aff, 10% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(42,0); //28% to pot, 18% to aff, 10% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D) potSplit_[0] = F3Ddatasets.PotSplit(42,0); //48% to winner, 0% to next round, 10% to com potSplit_[1] = F3Ddatasets.PotSplit(34,0); //48% to winner, 8% to next round, 10% to com potSplit_[2] = F3Ddatasets.PotSplit(18,0); //48% to winner, 24% to next round, 10% to com potSplit_[3] = F3Ddatasets.PotSplit(26,0); //48% to winner, 16% to next round, 10% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; uint256 _withdrawFee; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) { //10% trade tax _withdrawFee = _eth / 10; uint256 _p1 = _withdrawFee.mul(65) / 100; uint256 _p2 = _withdrawFee.mul(35) / 100; shareCom.transfer(_p1); admin.transfer(_p2); plyr_[_pID].addr.transfer(_eth.sub(_withdrawFee)); } // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) { //10% trade tax _withdrawFee = _eth / 10; _p1 = _withdrawFee.mul(65) / 100; _p2 = _withdrawFee.mul(35) / 100; shareCom.transfer(_p1); admin.transfer(_p2); plyr_[_pID].addr.transfer(_eth.sub(_withdrawFee)); } // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 100000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 10); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards shareCom.transfer((_com.mul(65) / 100)); admin.transfer((_com.mul(35) / 100)); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = 0; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; uint256 _rndInc = rndInc_; if(round_[_rID].pot > rndLimit_) { _rndInc = _rndInc / 2; } // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(_rndInc)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(_rndInc)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay community rewards uint256 _com = _eth / 10; uint256 _p3d; if (!address(admin).call.value(_com)()) { _p3d = _com; _com = 0; } // pay 1% out to FoMo3D short // uint256 _long = _eth / 100; // otherF3D_.potSwap.value(_long)(); _p3d = _p3d.add(distributeAff(_rID,_pID,_eth,_affID)); // pay out p3d // _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to divies contract uint256 _potAmount = _p3d / 2; uint256 _amount = _p3d.sub(_potAmount); shareCom.transfer((_amount.mul(65)/100)); admin.transfer((_amount.mul(35)/100)); round_[_rID].pot = round_[_rID].pot.add(_potAmount); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function distributeAff(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID) private returns(uint256) { uint256 _addP3d = 0; // distribute share to affiliate uint256 _aff1 = _eth / 10; uint256 _aff2 = _eth / 20; uint256 _aff3 = _eth / 34; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if ((_affID != 0) && (_affID != _pID) && (plyr_[_affID].name != '')) { plyr_[_pID].laffID = _affID; plyr_[_affID].aff = _aff1.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff1, now); //second level aff uint256 _secLaff = plyr_[_affID].laffID; if((_secLaff != 0) && (_secLaff != _pID)) { plyr_[_secLaff].aff = _aff2.add(plyr_[_secLaff].aff); emit F3Devents.onAffiliatePayout(_secLaff, plyr_[_secLaff].addr, plyr_[_secLaff].name, _rID, _pID, _aff2, now); //third level aff uint256 _thirdAff = plyr_[_secLaff].laffID; if((_thirdAff != 0 ) && (_thirdAff != _pID)) { plyr_[_thirdAff].aff = _aff3.add(plyr_[_thirdAff].aff); emit F3Devents.onAffiliatePayout(_thirdAff, plyr_[_thirdAff].addr, plyr_[_thirdAff].name, _rID, _pID, _aff3, now); } else { _addP3d = _addP3d.add(_aff3); } } else { _addP3d = _addP3d.add(_aff2); } } else { _addP3d = _addP3d.add(_aff1); } return(_addP3d); } function getPlayerAff(uint256 _pID) public view returns (uint256,uint256,uint256) { uint256 _affID = plyr_[_pID].laffID; if (_affID != 0) { //second level aff uint256 _secondLaff = plyr_[_affID].laffID; if(_secondLaff != 0) { //third level aff uint256 _thirdAff = plyr_[_secondLaff].laffID; } } return (_affID,_secondLaff,_thirdAff); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) //_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); _eth = _eth.sub(_eth.mul(30) / 100); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require(msg.sender == admin, "only admin can activate"); // can only be ran once require(activated_ == false, "FOMO Short already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used uint256 laffID; // last affiliate id unaffected } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library F3DKeysCalcShort { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
logic runs whenever a reload order is executed. determines how to handle incoming eth depending on if we are in an active round or not/ setup local rID grab time if round is active get earnings from all vaults and return unused to gen vault because we use a custom safemath library. this will throw if player tried to spend more eth than they have. call core if round is not active and end round needs to be ran end the round (distributes pot) & start new round build event data fire buy and distribute event
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); core(_rID, _pID, _eth, _affID, _team, _eventData_); round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } }
27,604
pragma solidity ^0.4.24; import './IBancorNetwork.sol'; import './ContractIds.sol'; import './FeatureIds.sol'; import './converter/interfaces/IBancorConverter.sol'; import './converter/interfaces/IBancorFormula.sol'; import './converter/interfaces/IBancorGasPriceLimit.sol'; import './utility/TokenHolder.sol'; import './utility/interfaces/IContractRegistry.sol'; import './utility/interfaces/IContractFeatures.sol'; import './utility/interfaces/IWhitelist.sol'; import './token/interfaces/IEtherToken.sol'; import './token/interfaces/ISmartToken.sol'; /* The BancorNetwork contract is the main entry point for bancor token conversions. It also allows converting between any token in the bancor network to any other token in a single transaction by providing a conversion path. A note on conversion path - Conversion path is a data structure that's used when converting a token to another token in the bancor network when the conversion cannot necessarily be done by single converter and might require multiple 'hops'. The path defines which converters should be used and what kind of conversion should be done in each step. The path format doesn't include complex structure and instead, it is represented by a single array in which each 'hop' is represented by a 2-tuple - smart token & to token. In addition, the first element is always the source token. The smart token is only used as a pointer to a converter (since converter addresses are more likely to change). Format: [source token, smart token, to token, smart token, to token...] */ contract BancorNetwork is IBancorNetwork, TokenHolder, ContractIds, FeatureIds { uint64 private constant MAX_CONVERSION_FEE = 1000000; address public signerAddress = 0x0; // verified address that allows conversions with higher gas price IContractRegistry public registry; // contract registry contract address mapping (address => bool) public etherTokens; // list of all supported ether tokens mapping (bytes32 => bool) public conversionHashes; // list of conversion hashes, to prevent re-use of the same hash /** @dev constructor @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) public validAddress(_registry) { registry = _registry; } // validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10 modifier validConversionPath(IERC20Token[] _path) { require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1); _; } /* @dev allows the owner to update the contract registry contract address @param _registry address of a contract registry contract */ function setRegistry(IContractRegistry _registry) public ownerOnly validAddress(_registry) notThis(_registry) { registry = _registry; } /* @dev allows the owner to update the signer address @param _signerAddress new signer address */ function setSignerAddress(address _signerAddress) public ownerOnly validAddress(_signerAddress) notThis(_signerAddress) { signerAddress = _signerAddress; } /** @dev allows the owner to register/unregister ether tokens @param _token ether token contract address @param _register true to register, false to unregister */ function registerEtherToken(IEtherToken _token, bool _register) public ownerOnly validAddress(_token) notThis(_token) { etherTokens[_token] = _register; } /** @dev verifies that the signer address is trusted by recovering the address associated with the public key from elliptic curve signature, returns zero on error. notice that the signature is valid only for one conversion and expires after the give block. @return true if the signer is verified */ function verifyTrustedSender(IERC20Token[] _path, uint256 _amount, uint256 _block, address _addr, uint8 _v, bytes32 _r, bytes32 _s) private returns(bool) { bytes32 hash = keccak256(_block, tx.gasprice, _addr, msg.sender, _amount, _path); // checking that it is the first conversion with the given signature // and that the current block number doesn't exceeded the maximum block // number that's allowed with the current signature require(!conversionHashes[hash] && block.number <= _block); // recovering the signing address and comparing it to the trusted signer // address that was set in the contract bytes32 prefixedHash = keccak256("\x19Ethereum Signed Message:\n32", hash); bool verified = ecrecover(prefixedHash, _v, _r, _s) == signerAddress; // if the signer is the trusted signer - mark the hash so that it can't // be used multiple times if (verified) conversionHashes[hash] = true; return verified; } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path and transfers the result tokens to a target account note that the converter should already own the source tokens @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversion result @return tokens issued in return */ function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256) { return convertForPrioritized2(_path, _amount, _minReturn, _for, 0x0, 0x0, 0x0, 0x0); } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path and transfers the result tokens to a target account. this version of the function also allows the verified signer to bypass the universal gas price limit. note that the converter should already own the source tokens @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversion result @return tokens issued in return */ function convertForPrioritized2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public payable validConversionPath(_path) returns (uint256) { // if ETH is provided, ensure that the amount is identical to _amount and verify that the source token is an ether token IERC20Token fromToken = _path[0]; require(msg.value == 0 || (_amount == msg.value && etherTokens[fromToken])); // if ETH was sent with the call, the source is an ether token - deposit the ETH in it // otherwise, we assume we already have the tokens if (msg.value > 0) IEtherToken(fromToken).deposit.value(msg.value)(); return convertForInternal(_path, _amount, _minReturn, _for, _block, _v, _r, _s); } /** @dev converts token to any other token in the bancor network by following the predefined conversion paths and transfers the result tokens to a targeted account. this version of the function also allows multiple conversions in a single atomic transaction. note that the converter should already own the source tokens @param _paths merged conversion paths, i.e. [path1, path2, ...]. see conversion path format above @param _pathStartIndex each item in the array is the start index of the nth path in _paths @param _amounts amount to convert from (in the initial source token) for each path @param _minReturns minimum return for each path. if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversions result @return amount of conversion result for each path */ function convertForMultiple(IERC20Token[] _paths, uint256[] _pathStartIndex, uint256[] _amounts, uint256[] _minReturns, address _for) public payable returns (uint256[]) { // if ETH is provided, ensure that the total amount was converted into other tokens uint256 convertedValue = 0; uint256 pathEndIndex; // iterate over the conversion paths for (uint256 i = 0; i < _pathStartIndex.length; i += 1) { pathEndIndex = i == (_pathStartIndex.length - 1) ? _paths.length : _pathStartIndex[i + 1]; // copy a single path from _paths into an array IERC20Token[] memory path = new IERC20Token[](pathEndIndex - _pathStartIndex[i]); for (uint256 j = _pathStartIndex[i]; j < pathEndIndex; j += 1) { path[j - _pathStartIndex[i]] = _paths[j]; } // if ETH is provided, ensure that the amount is lower than the path amount and // verify that the source token is an ether token. otherwise ensure that // the source is not an ether token IERC20Token fromToken = path[0]; require(msg.value == 0 || (_amounts[i] <= msg.value && etherTokens[fromToken]) || !etherTokens[fromToken]); // if ETH was sent with the call, the source is an ether token - deposit the ETH path amount in it. // otherwise, we assume we already have the tokens if (msg.value > 0 && etherTokens[fromToken]) { IEtherToken(fromToken).deposit.value(_amounts[i])(); convertedValue += _amounts[i]; } _amounts[i] = convertForInternal(path, _amounts[i], _minReturns[i], _for, 0x0, 0x0, 0x0, 0x0); } // if ETH was provided, ensure that the full amount was converted require(convertedValue == msg.value); return _amounts; } /** @dev converts token to any other token in the bancor network by following a predefined conversion paths and transfers the result tokens to a target account. @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversion result @param _block if the current block exceeded the given parameter - it is cancelled @param _v (signature[128:130]) associated with the signer address and helps to validate if the signature is legit @param _r (signature[0:64]) associated with the signer address and helps to validate if the signature is legit @param _s (signature[64:128]) associated with the signer address and helps to validate if the signature is legit @return tokens issued in return */ function convertForInternal( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s ) private validConversionPath(_path) returns (uint256) { if (_v == 0x0 && _r == 0x0 && _s == 0x0) { IBancorGasPriceLimit gasPriceLimit = IBancorGasPriceLimit(registry.addressOf(ContractIds.BANCOR_GAS_PRICE_LIMIT)); gasPriceLimit.validateGasPrice(tx.gasprice); } else { require(verifyTrustedSender(_path, _amount, _block, _for, _v, _r, _s)); } // if ETH is provided, ensure that the amount is identical to _amount and verify that the source token is an ether token IERC20Token fromToken = _path[0]; IERC20Token toToken; (toToken, _amount) = convertByPath(_path, _amount, _minReturn, fromToken, _for); // finished the conversion, transfer the funds to the target account // if the target token is an ether token, withdraw the tokens and send them as ETH // otherwise, transfer the tokens as is if (etherTokens[toToken]) IEtherToken(toToken).withdrawTo(_for, _amount); else assert(toToken.transfer(_for, _amount)); return _amount; } /** @dev executes the actual conversion by following the conversion path @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _fromToken ERC20 token to convert from (the first element in the path) @param _for account that will receive the conversion result @return ERC20 token to convert to (the last element in the path) & tokens issued in return */ function convertByPath( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, IERC20Token _fromToken, address _for ) private returns (IERC20Token, uint256) { ISmartToken smartToken; IERC20Token toToken; IBancorConverter converter; // get the contract features address from the registry IContractFeatures features = IContractFeatures(registry.addressOf(ContractIds.CONTRACT_FEATURES)); // iterate over the conversion path uint256 pathLength = _path.length; for (uint256 i = 1; i < pathLength; i += 2) { smartToken = ISmartToken(_path[i]); toToken = _path[i + 1]; converter = IBancorConverter(smartToken.owner()); checkWhitelist(converter, _for, features); // if the smart token isn't the source (from token), the converter doesn't have control over it and thus we need to approve the request if (smartToken != _fromToken) ensureAllowance(_fromToken, converter, _amount); // make the conversion - if it's the last one, also provide the minimum return value _amount = converter.change(_fromToken, toToken, _amount, i == pathLength - 2 ? _minReturn : 1); _fromToken = toToken; } return (toToken, _amount); } /** @dev returns the expected return amount for converting a specific amount by following a given conversion path. notice that there is no support for circular paths. @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @return expected conversion return amount and conversion fee */ function getReturnByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256, uint256) { IERC20Token fromToken; ISmartToken smartToken; IERC20Token toToken; IBancorConverter converter; uint256 amount; uint256 fee; uint256 supply; uint256 balance; uint32 weight; ISmartToken prevSmartToken; IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA)); amount = _amount; fromToken = _path[0]; // iterate over the conversion path for (uint256 i = 1; i < _path.length; i += 2) { smartToken = ISmartToken(_path[i]); toToken = _path[i + 1]; converter = IBancorConverter(smartToken.owner()); if (toToken == smartToken) { // buy the smart token // check if the current smart token supply was changed in the previous iteration supply = smartToken == prevSmartToken ? supply : smartToken.totalSupply(); // validate input require(getConnectorPurchaseEnabled(converter, fromToken)); // calculate the amount & the conversion fee balance = converter.getConnectorBalance(fromToken); weight = getConnectorWeight(converter, fromToken); amount = formula.calculatePurchaseReturn(supply, balance, weight, amount); fee = safeMul(amount, converter.conversionFee()) / MAX_CONVERSION_FEE; amount -= fee; // update the smart token supply for the next iteration supply = smartToken.totalSupply() + amount; } else if (fromToken == smartToken) { // sell the smart token // check if the current smart token supply was changed in the previous iteration supply = smartToken == prevSmartToken ? supply : smartToken.totalSupply(); // calculate the amount & the conversion fee balance = converter.getConnectorBalance(toToken); weight = getConnectorWeight(converter, toToken); amount = formula.calculateSaleReturn(supply, balance, weight, amount); fee = safeMul(amount, converter.conversionFee()) / MAX_CONVERSION_FEE; amount -= fee; // update the smart token supply for the next iteration supply = smartToken.totalSupply() - amount; } else { // cross connector conversion (amount, fee) = converter.getReturn(fromToken, toToken, amount); } prevSmartToken = smartToken; fromToken = toToken; } return (amount, fee); } /** @dev checks whether the given converter supports a whitelist and if so, ensures that the account that should receive the conversion result is actually whitelisted @param _converter converter to check for whitelist @param _for account that will receive the conversion result @param _features contract features contract address */ function checkWhitelist(IBancorConverter _converter, address _for, IContractFeatures _features) private view { IWhitelist whitelist; // check if the converter supports the conversion whitelist feature if (!_features.isSupported(_converter, FeatureIds.CONVERTER_CONVERSION_WHITELIST)) return; // get the whitelist contract from the converter whitelist = _converter.conversionWhitelist(); if (whitelist == address(0)) return; // check if the account that should receive the conversion result is actually whitelisted require(whitelist.isWhitelisted(_for)); } /** @dev claims the caller's tokens, converts them to any other token in the bancor network by following a predefined conversion path and transfers the result tokens to a target account note that allowance must be set beforehand @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversion result @return tokens issued in return */ function claimAndConvertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public returns (uint256) { // we need to transfer the tokens from the caller to the converter before we follow // the conversion path, to allow it to execute the conversion on behalf of the caller // note: we assume we already have allowance IERC20Token fromToken = _path[0]; assert(fromToken.transferFrom(msg.sender, this, _amount)); return convertFor(_path, _amount, _minReturn, _for); } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path and transfers the result tokens back to the sender note that the converter should already own the source tokens @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return tokens issued in return */ function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256) { return convertFor(_path, _amount, _minReturn, msg.sender); } /** @dev claims the caller's tokens, converts them to any other token in the bancor network by following a predefined conversion path and transfers the result tokens back to the sender note that allowance must be set beforehand @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return tokens issued in return */ function claimAndConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public returns (uint256) { return claimAndConvertFor(_path, _amount, _minReturn, msg.sender); } /** @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't @param _token token to check the allowance in @param _spender approved address @param _value allowance amount */ function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private { // check if allowance for the given amount already exists if (_token.allowance(this, _spender) >= _value) return; // if the allowance is nonzero, must reset it to 0 first if (_token.allowance(this, _spender) != 0) assert(_token.approve(_spender, 0)); // approve the new allowance assert(_token.approve(_spender, _value)); } /** @dev returns the connector weight @param _converter converter contract address @param _connector connector's address to read from @return connector's weight */ function getConnectorWeight(IBancorConverter _converter, IERC20Token _connector) private view returns(uint32) { uint256 virtualBalance; uint32 weight; bool isVirtualBalanceEnabled; bool isPurchaseEnabled; bool isSet; (virtualBalance, weight, isVirtualBalanceEnabled, isPurchaseEnabled, isSet) = _converter.connectors(_connector); return weight; } /** @dev returns true if connector purchase enabled @param _converter converter contract address @param _connector connector's address to read from @return true if connector purchase enabled, otherwise - false */ function getConnectorPurchaseEnabled(IBancorConverter _converter, IERC20Token _connector) private view returns(bool) { uint256 virtualBalance; uint32 weight; bool isVirtualBalanceEnabled; bool isPurchaseEnabled; bool isSet; (virtualBalance, weight, isVirtualBalanceEnabled, isPurchaseEnabled, isSet) = _converter.connectors(_connector); return isPurchaseEnabled; } // deprecated, backward compatibility function convertForPrioritized( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256) { _nonce; return convertForPrioritized2(_path, _amount, _minReturn, _for, _block, _v, _r, _s); } }
/ iterate over the conversion path check if the current smart token supply was changed in the previous iteration validate input calculate the amount & the conversion fee update the smart token supply for the next iteration
function getReturnByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256, uint256) { IERC20Token fromToken; ISmartToken smartToken; IERC20Token toToken; IBancorConverter converter; uint256 amount; uint256 fee; uint256 supply; uint256 balance; uint32 weight; ISmartToken prevSmartToken; IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA)); amount = _amount; fromToken = _path[0]; for (uint256 i = 1; i < _path.length; i += 2) { smartToken = ISmartToken(_path[i]); toToken = _path[i + 1]; converter = IBancorConverter(smartToken.owner()); supply = smartToken == prevSmartToken ? supply : smartToken.totalSupply(); require(getConnectorPurchaseEnabled(converter, fromToken)); balance = converter.getConnectorBalance(fromToken); weight = getConnectorWeight(converter, fromToken); amount = formula.calculatePurchaseReturn(supply, balance, weight, amount); fee = safeMul(amount, converter.conversionFee()) / MAX_CONVERSION_FEE; amount -= fee; supply = smartToken.totalSupply() + amount; } weight = getConnectorWeight(converter, toToken); amount = formula.calculateSaleReturn(supply, balance, weight, amount); fee = safeMul(amount, converter.conversionFee()) / MAX_CONVERSION_FEE; amount -= fee; } (amount, fee) = converter.getReturn(fromToken, toToken, amount);
7,322,291
./full_match/83/0x518d0bD24C3d9705608f229BbfBAA4519d324628/sources/contracts/UnderWriterAdmin.sol
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, 'only pause guardian and admin can pause'); require(msg.sender == admin || state, 'only admin can unpause'); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, 'Borrow', state); return state; }
9,563,678
./full_match/1/0x3c53bd8809C220412BCac552CE09a7B2B786dD6A/sources/localhost/contracts/JT9.sol
msg sender should be DF9T clone contract mint DF9 and transfer prize to accout
function redeem(address account, uint256 level, uint256 id, uint256 dividend, bool mintable) external { require(factory.isVerifiedMarket(address(msg.sender))); if (mintable) { _mint(account, id, 1, ""); userInfo[account].redeemedBets.push( RedeemedBet({ id: id, level: level, cardType: "DF9", time: block.timestamp }) ); emit NewSynCardGenerated(account, level, id, block.timestamp); } if (dividend > 0) { jt.safeTransfer(account, dividend); } }
8,317,257
pragma solidity ^0.4.23; // import 'zeppelin-solidity/contracts/ownership/DelayedClaimable.sol'; import './MultiOwnerContract.sol'; interface itoken { function freezeAccount(address _target, bool _freeze) external; function freezeAccountPartialy(address _target, uint256 _value) external; function balanceOf(address _owner) external view returns (uint256 balance); // function totalSupply() external view returns (uint256); // function transferOwnership(address newOwner) external; function allowance(address _owner, address _spender) external view returns (uint256); function initialCongress(address _congress) external; function mint(address _to, uint256 _amount) external returns (bool); function finishMinting() external returns (bool); function pause() external; function unpause() external; } // interface iParams { // function reMintCap() external view returns (uint256); // function onceMintRate() external view returns (uint256); // } contract DRCTOwner is MultiOwnerContract { string public constant AUTH_INITCONGRESS = "initCongress"; string public constant AUTH_CANMINT = "canMint"; string public constant AUTH_SETMINTAMOUNT = "setMintAmount"; string public constant AUTH_FREEZEACCOUNT = "freezeAccount"; bool congressInit = false; // bool paramsInit = false; // iParams public params; uint256 onceMintAmount; // function initParams(address _params) onlyOwner public { // require(!paramsInit); // require(_params != address(0)); // params = _params; // paramsInit = false; // } /** * @dev Function to set mint token amount * @param _value The mint value. */ function setOnceMintAmount(uint256 _value) onlyMultiOwners public { require(hasAuth(AUTH_SETMINTAMOUNT)); require(_value > 0); onceMintAmount = _value; clearAuth(AUTH_SETMINTAMOUNT); } /** * @dev change the owner of the contract from this contract address to another one. * * @param _congress the contract address that will be next Owner of the original Contract */ function initCongress(address _congress) onlyMultiOwners public { require(hasAuth(AUTH_INITCONGRESS)); require(!congressInit); itoken tk = itoken(address(ownedContract)); tk.initialCongress(_congress); clearAuth(AUTH_INITCONGRESS); congressInit = true; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @return A boolean that indicates if the operation was successful. */ function mint(address _to) onlyMultiOwners public returns (bool) { require(hasAuth(AUTH_CANMINT)); itoken tk = itoken(address(ownedContract)); bool res = tk.mint(_to, onceMintAmount); clearAuth(AUTH_CANMINT); return res; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyMultiOwners public returns (bool) { require(hasAuth(AUTH_CANMINT)); itoken tk = itoken(address(ownedContract)); bool res = tk.finishMinting(); clearAuth(AUTH_CANMINT); return res; } /** * @dev freeze the account's balance under urgent situation * * by default all the accounts will not be frozen until set freeze value as true. * * @param _target address the account should be frozen * @param _freeze bool if true, the account will be frozen */ function freezeAccountDirect(address _target, bool _freeze) onlyMultiOwners public { require(hasAuth(AUTH_FREEZEACCOUNT)); require(_target != address(0)); itoken tk = itoken(address(ownedContract)); tk.freezeAccount(_target, _freeze); clearAuth(AUTH_FREEZEACCOUNT); } /** * @dev freeze the account's balance * * by default all the accounts will not be frozen until set freeze value as true. * * @param _target address the account should be frozen * @param _freeze bool if true, the account will be frozen */ function freezeAccount(address _target, bool _freeze) onlyOwner public { require(_target != address(0)); itoken tk = itoken(address(ownedContract)); if (_freeze) { require(tk.allowance(_target, this) == tk.balanceOf(_target)); } tk.freezeAccount(_target, _freeze); } /** * @dev freeze the account's balance * * @param _target address the account should be frozen * @param _value uint256 the amount of tokens that will be frozen */ function freezeAccountPartialy(address _target, uint256 _value) onlyOwner public { require(_target != address(0)); itoken tk = itoken(address(ownedContract)); require(tk.allowance(_target, this) == _value); tk.freezeAccountPartialy(_target, _value); } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner public { itoken tk = itoken(address(ownedContract)); tk.pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner public { itoken tk = itoken(address(ownedContract)); tk.unpause(); } }
change the owner of the contract from this contract address to another one. _congress the contract address that will be next Owner of the original Contract/
function initCongress(address _congress) onlyMultiOwners public { require(hasAuth(AUTH_INITCONGRESS)); require(!congressInit); itoken tk = itoken(address(ownedContract)); tk.initialCongress(_congress); clearAuth(AUTH_INITCONGRESS); congressInit = true; }
5,386,564
pragma solidity 0.8.3; import "./CurrencyNetworkInterface.sol"; contract TLSwap { CurrencyNetworkInterface _currency; struct Commitment { address payable initiator; address payable recipient; address TLNetwork; uint64 TLMoneyAmount; uint64 endTimeStamp; address initiatorEthAddress; uint256 EthAmount; } mapping(bytes32 => Commitment) public CommitmentsMap; // the key is the hash event Commit(bytes32 indexed hash, address sender, address receiver, address TLNetwork, uint256 TLMoneyAmount, uint64 expiryTime); event Claim(bytes32 indexed hash, address sender, address receiver, address TLNetwork, uint256 TLMoneyAmount); event ExpireCommitment(bytes32 indexed hash); function commit(address payable _TLRecipient, address _TLNetwork, uint64 _TLMoneyAmount, address _InitiatorEthAddress, uint _EthAmount, uint64 _lockTimeSec, bytes32 _hash) external { require(CommitmentsMap[_hash].initiator == address(0x0), "Entry already exists"); require(_TLMoneyAmount > 0, "TL total money amount is required"); require(_InitiatorEthAddress != address(0x0), "Ethereum address is required"); require(_EthAmount > 0, "Eth total amount is required"); uint64 expiryTime = uint64(block.timestamp + _lockTimeSec); CommitmentsMap[_hash].initiator = payable(msg.sender); CommitmentsMap[_hash].recipient = _TLRecipient; CommitmentsMap[_hash].endTimeStamp = expiryTime; CommitmentsMap[_hash].TLMoneyAmount = _TLMoneyAmount; CommitmentsMap[_hash].TLNetwork =_TLNetwork; CommitmentsMap[_hash].initiatorEthAddress = _InitiatorEthAddress; CommitmentsMap[_hash].EthAmount = _EthAmount; emit Commit(_hash, msg.sender, _TLRecipient, _TLNetwork, _TLMoneyAmount, expiryTime); } function claim(address[] calldata _path, uint64 _maxFee, bytes calldata _extraData, bytes32 _proof) external { bytes32 hash = keccak256(abi.encodePacked(_proof)); require(CommitmentsMap[hash].initiator != address(0x0), "No entry found"); require(CommitmentsMap[hash].endTimeStamp >= block.timestamp, "TimeStamp violation"); require(CommitmentsMap[hash].recipient == msg.sender, "Claim msg sender must be recipient"); require(CommitmentsMap[hash].initiator == _path[0], "Path must start with commitment sender"); require(CommitmentsMap[hash].recipient == _path[_path.length - 1], "Path must end with commitment recipient"); address networkAddress = CommitmentsMap[hash].TLNetwork; uint64 TlMoneyAmount = CommitmentsMap[hash].TLMoneyAmount; delete CommitmentsMap[hash]; _currency = CurrencyNetworkInterface(networkAddress); _currency.transferFrom(TlMoneyAmount, _maxFee, _path, _extraData); emit Claim(hash, _path[0], _path[_path.length - 1], networkAddress, TlMoneyAmount); } /* * We currently just remove the commitment. In the future we could * make sure that if a transfer didn't succeed we could add a dept * in the currency network */ function removeCommitment(bytes32 _hash) external { require(CommitmentsMap[_hash].initiator != address(0x0), "No entry found"); require(CommitmentsMap[_hash].endTimeStamp < block.timestamp, "TimeStamp violation"); delete CommitmentsMap[_hash]; emit ExpireCommitment(_hash); } } // SPDX-License-Identifier: MIT
We currently just remove the commitment. In the future we could make sure that if a transfer didn't succeed we could add a dept in the currency network/
function removeCommitment(bytes32 _hash) external { require(CommitmentsMap[_hash].initiator != address(0x0), "No entry found"); require(CommitmentsMap[_hash].endTimeStamp < block.timestamp, "TimeStamp violation"); delete CommitmentsMap[_hash]; emit ExpireCommitment(_hash); }
12,643,901
// 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; } } }
Get market total borrows from the AlkemiEarnVerified contract market The address of the market 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; }
81,710
pragma solidity ^0.4.23; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "Overflow - Multiplication"); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "Underflow - Subtraction"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "Overflow - Addition"); return c; } } library Contract { using SafeMath for uint; // Modifiers: // // Runs two functions before and after a function - modifier conditions(function () pure first, function () pure last) { first(); _; last(); } bytes32 internal constant EXEC_PERMISSIONS = keccak256('script_exec_permissions'); // Sets up contract execution - reads execution id and sender from storage and // places in memory, creating getters. Calling this function should be the first // action an application does as part of execution, as it sets up memory for // execution. Additionally, application functions in the main file should be // external, so that memory is not touched prior to calling this function. // The 3rd slot allocated will hold a pointer to a storage buffer, which will // be reverted to abstract storage to store data, emit events, and forward // wei on behalf of the application. function authorize(address _script_exec) internal view { // Initialize memory initialize(); // Check that the sender is authorized as a script exec contract for this exec id bytes32 perms = EXEC_PERMISSIONS; bool authorized; assembly { // Place the script exec address at 0, and the exec permissions seed after it mstore(0, _script_exec) mstore(0x20, perms) // Hash the resulting 0x34 bytes, and place back into memory at 0 mstore(0, keccak256(0x0c, 0x34)) // Place the exec id after the hash - mstore(0x20, mload(0x80)) // Hash the previous hash with the execution id, and check the result authorized := sload(keccak256(0, 0x40)) } if (!authorized) revert("Sender is not authorized as a script exec address"); } // Sets up contract execution when initializing an instance of the application // First, reads execution id and sender from storage (execution id should be 0xDEAD), // then places them in memory, creating getters. Calling this function should be the first // action an application does as part of execution, as it sets up memory for // execution. Additionally, application functions in the main file should be // external, so that memory is not touched prior to calling this function. // The 3rd slot allocated will hold a pointer to a storage buffer, which will // be reverted to abstract storage to store data, emit events, and forward // wei on behalf of the application. function initialize() internal view { // No memory should have been allocated yet - expect the free memory pointer // to point to 0x80 - and throw if it does not require(freeMem() == 0x80, "Memory allocated prior to execution"); // Next, set up memory for execution assembly { mstore(0x80, sload(0)) // Execution id, read from storage mstore(0xa0, sload(1)) // Original sender address, read from storage mstore(0xc0, 0) // Pointer to storage buffer mstore(0xe0, 0) // Bytes4 value of the current action requestor being used mstore(0x100, 0) // Enum representing the next type of function to be called (when pushing to buffer) mstore(0x120, 0) // Number of storage slots written to in buffer mstore(0x140, 0) // Number of events pushed to buffer mstore(0x160, 0) // Number of payment destinations pushed to buffer // Update free memory pointer - mstore(0x40, 0x180) } // Ensure that the sender and execution id returned from storage are expected values - assert(execID() != bytes32(0) && sender() != address(0)); } // Calls the passed-in function, performing a memory state check before and after the check // is executed. function checks(function () view _check) conditions(validState, validState) internal view { _check(); } // Calls the passed-in function, performing a memory state check before and after the check // is executed. function checks(function () pure _check) conditions(validState, validState) internal pure { _check(); } // Ensures execution completed successfully, and reverts the created storage buffer // back to the sender. function commit() conditions(validState, none) internal pure { // Check value of storage buffer pointer - should be at least 0x180 bytes32 ptr = buffPtr(); require(ptr >= 0x180, "Invalid buffer pointer"); assembly { // Get the size of the buffer let size := mload(add(0x20, ptr)) mstore(ptr, 0x20) // Place dynamic data offset before buffer // Revert to storage revert(ptr, add(0x40, size)) } } // Helpers: // // Checks to ensure the application was correctly executed - function validState() private pure { if (freeMem() < 0x180) revert('Expected Contract.execute()'); if (buffPtr() != 0 && buffPtr() < 0x180) revert('Invalid buffer pointer'); assert(execID() != bytes32(0) && sender() != address(0)); } // Returns a pointer to the execution storage buffer - function buffPtr() private pure returns (bytes32 ptr) { assembly { ptr := mload(0xc0) } } // Returns the location pointed to by the free memory pointer - function freeMem() private pure returns (bytes32 ptr) { assembly { ptr := mload(0x40) } } // Returns the current storage action function currentAction() private pure returns (bytes4 action) { if (buffPtr() == bytes32(0)) return bytes4(0); assembly { action := mload(0xe0) } } // If the current action is not storing, reverts function isStoring() private pure { if (currentAction() != STORES) revert('Invalid current action - expected STORES'); } // If the current action is not emitting, reverts function isEmitting() private pure { if (currentAction() != EMITS) revert('Invalid current action - expected EMITS'); } // If the current action is not paying, reverts function isPaying() private pure { if (currentAction() != PAYS) revert('Invalid current action - expected PAYS'); } // Initializes a storage buffer in memory - function startBuffer() private pure { assembly { // Get a pointer to free memory, and place at 0xc0 (storage buffer pointer) let ptr := msize() mstore(0xc0, ptr) // Clear bytes at pointer - mstore(ptr, 0) // temp ptr mstore(add(0x20, ptr), 0) // buffer length // Update free memory pointer - mstore(0x40, add(0x40, ptr)) // Set expected next function to 'NONE' - mstore(0x100, 1) } } // Checks whether or not it is valid to create a STORES action request - function validStoreBuff() private pure { // Get pointer to current buffer - if zero, create a new buffer - if (buffPtr() == bytes32(0)) startBuffer(); // Ensure that the current action is not 'storing', and that the buffer has not already // completed a STORES action - if (stored() != 0 || currentAction() == STORES) revert('Duplicate request - stores'); } // Checks whether or not it is valid to create an EMITS action request - function validEmitBuff() private pure { // Get pointer to current buffer - if zero, create a new buffer - if (buffPtr() == bytes32(0)) startBuffer(); // Ensure that the current action is not 'emitting', and that the buffer has not already // completed an EMITS action - if (emitted() != 0 || currentAction() == EMITS) revert('Duplicate request - emits'); } // Checks whether or not it is valid to create a PAYS action request - function validPayBuff() private pure { // Get pointer to current buffer - if zero, create a new buffer - if (buffPtr() == bytes32(0)) startBuffer(); // Ensure that the current action is not 'paying', and that the buffer has not already // completed an PAYS action - if (paid() != 0 || currentAction() == PAYS) revert('Duplicate request - pays'); } // Placeholder function when no pre or post condition for a function is needed function none() private pure { } // Runtime getters: // // Returns the execution id from memory - function execID() internal pure returns (bytes32 exec_id) { assembly { exec_id := mload(0x80) } require(exec_id != bytes32(0), "Execution id overwritten, or not read"); } // Returns the original sender from memory - function sender() internal pure returns (address addr) { assembly { addr := mload(0xa0) } require(addr != address(0), "Sender address overwritten, or not read"); } // Reading from storage: // // Reads from storage, resolving the passed-in location to its true location in storage // by hashing with the exec id. Returns the data read from that location function read(bytes32 _location) internal view returns (bytes32 data) { data = keccak256(_location, execID()); assembly { data := sload(data) } } // Storing data, emitting events, and forwarding payments: // bytes4 internal constant EMITS = bytes4(keccak256('Emit((bytes32[],bytes)[])')); bytes4 internal constant STORES = bytes4(keccak256('Store(bytes32[])')); bytes4 internal constant PAYS = bytes4(keccak256('Pay(bytes32[])')); bytes4 internal constant THROWS = bytes4(keccak256('Error(string)')); // Function enums - enum NextFunction { INVALID, NONE, STORE_DEST, VAL_SET, VAL_INC, VAL_DEC, EMIT_LOG, PAY_DEST, PAY_AMT } // Checks that a call pushing a storage destination to the buffer is expected and valid function validStoreDest() private pure { // Ensure that the next function expected pushes a storage destination - if (expected() != NextFunction.STORE_DEST) revert('Unexpected function order - expected storage destination to be pushed'); // Ensure that the current buffer is pushing STORES actions - isStoring(); } // Checks that a call pushing a storage value to the buffer is expected and valid function validStoreVal() private pure { // Ensure that the next function expected pushes a storage value - if ( expected() != NextFunction.VAL_SET && expected() != NextFunction.VAL_INC && expected() != NextFunction.VAL_DEC ) revert('Unexpected function order - expected storage value to be pushed'); // Ensure that the current buffer is pushing STORES actions - isStoring(); } // Checks that a call pushing a payment destination to the buffer is expected and valid function validPayDest() private pure { // Ensure that the next function expected pushes a payment destination - if (expected() != NextFunction.PAY_DEST) revert('Unexpected function order - expected payment destination to be pushed'); // Ensure that the current buffer is pushing PAYS actions - isPaying(); } // Checks that a call pushing a payment amount to the buffer is expected and valid function validPayAmt() private pure { // Ensure that the next function expected pushes a payment amount - if (expected() != NextFunction.PAY_AMT) revert('Unexpected function order - expected payment amount to be pushed'); // Ensure that the current buffer is pushing PAYS actions - isPaying(); } // Checks that a call pushing an event to the buffer is expected and valid function validEvent() private pure { // Ensure that the next function expected pushes an event - if (expected() != NextFunction.EMIT_LOG) revert('Unexpected function order - expected event to be pushed'); // Ensure that the current buffer is pushing EMITS actions - isEmitting(); } // Begins creating a storage buffer - values and locations pushed will be committed // to storage at the end of execution function storing() conditions(validStoreBuff, isStoring) internal pure { bytes4 action_req = STORES; assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push requestor to the end of buffer, as well as to the 'current action' slot - mstore(add(0x20, add(ptr, mload(ptr))), action_req) // Push '0' to the end of the 4 bytes just pushed - this will be the length of the STORES action mstore(add(0x24, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x24 plus the previous length mstore(ptr, add(0x24, mload(ptr))) // Set the current action being executed (STORES) - mstore(0xe0, action_req) // Set the expected next function - STORE_DEST mstore(0x100, 2) // Set a pointer to the length of the current request within the buffer mstore(sub(ptr, 0x20), add(ptr, mload(ptr))) } // Update free memory pointer setFreeMem(); } // Sets a passed in location to a value passed in via 'to' function set(bytes32 _field) conditions(validStoreDest, validStoreVal) internal pure returns (bytes32) { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage destination to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _field) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - VAL_SET mstore(0x100, 3) // Increment STORES action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of storage slots pushed to - mstore(0x120, add(1, mload(0x120))) } // Update free memory pointer setFreeMem(); return _field; } // Sets a previously-passed-in destination in storage to the value function to(bytes32, bytes32 _val) conditions(validStoreVal, validStoreDest) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage value to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _val) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - STORE_DEST mstore(0x100, 2) } // Update free memory pointer setFreeMem(); } // Sets a previously-passed-in destination in storage to the value function to(bytes32 _field, uint _val) internal pure { to(_field, bytes32(_val)); } // Sets a previously-passed-in destination in storage to the value function to(bytes32 _field, address _val) internal pure { to(_field, bytes32(_val)); } // Sets a previously-passed-in destination in storage to the value function to(bytes32 _field, bool _val) internal pure { to( _field, _val ? bytes32(1) : bytes32(0) ); } function increase(bytes32 _field) conditions(validStoreDest, validStoreVal) internal view returns (bytes32 val) { // Read value stored at the location in storage - val = keccak256(_field, execID()); assembly { val := sload(val) // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage destination to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _field) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - VAL_INC mstore(0x100, 4) // Increment STORES action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of storage slots pushed to - mstore(0x120, add(1, mload(0x120))) } // Update free memory pointer setFreeMem(); return val; } function decrease(bytes32 _field) conditions(validStoreDest, validStoreVal) internal view returns (bytes32 val) { // Read value stored at the location in storage - val = keccak256(_field, execID()); assembly { val := sload(val) // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage destination to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _field) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - VAL_DEC mstore(0x100, 5) // Increment STORES action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of storage slots pushed to - mstore(0x120, add(1, mload(0x120))) } // Update free memory pointer setFreeMem(); return val; } function by(bytes32 _val, uint _amt) conditions(validStoreVal, validStoreDest) internal pure { // Check the expected function type - if it is VAL_INC, perform safe-add on the value // If it is VAL_DEC, perform safe-sub on the value if (expected() == NextFunction.VAL_INC) _amt = _amt.add(uint(_val)); else if (expected() == NextFunction.VAL_DEC) _amt = uint(_val).sub(_amt); else revert('Expected VAL_INC or VAL_DEC'); assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage value to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _amt) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - STORE_DEST mstore(0x100, 2) } // Update free memory pointer setFreeMem(); } // Decreases the value at some field by a maximum amount, and sets it to 0 if there will be underflow function byMaximum(bytes32 _val, uint _amt) conditions(validStoreVal, validStoreDest) internal pure { // Check the expected function type - if it is VAL_DEC, set the new amount to the difference of // _val and _amt, to a minimum of 0 if (expected() == NextFunction.VAL_DEC) { if (_amt >= uint(_val)) _amt = 0; else _amt = uint(_val).sub(_amt); } else { revert('Expected VAL_DEC'); } assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage value to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _amt) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - STORE_DEST mstore(0x100, 2) } // Update free memory pointer setFreeMem(); } // Begins creating an event log buffer - topics and data pushed will be emitted by // storage at the end of execution function emitting() conditions(validEmitBuff, isEmitting) internal pure { bytes4 action_req = EMITS; assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push requestor to the end of buffer, as well as to the 'current action' slot - mstore(add(0x20, add(ptr, mload(ptr))), action_req) // Push '0' to the end of the 4 bytes just pushed - this will be the length of the EMITS action mstore(add(0x24, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x24 plus the previous length mstore(ptr, add(0x24, mload(ptr))) // Set the current action being executed (EMITS) - mstore(0xe0, action_req) // Set the expected next function - EMIT_LOG mstore(0x100, 6) // Set a pointer to the length of the current request within the buffer mstore(sub(ptr, 0x20), add(ptr, mload(ptr))) } // Update free memory pointer setFreeMem(); } function log(bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push 0 to the end of the buffer - event will have 0 topics mstore(add(0x20, add(ptr, mload(ptr))), 0) // If _data is zero, set data size to 0 in buffer and push - if eq(_data, 0) { mstore(add(0x40, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x40 plus the original length mstore(ptr, add(0x40, mload(ptr))) } // If _data is not zero, set size to 0x20 and push to buffer - if iszero(eq(_data, 0)) { // Push data size (0x20) to the end of the buffer mstore(add(0x40, add(ptr, mload(ptr))), 0x20) // Push data to the end of the buffer mstore(add(0x60, add(ptr, mload(ptr))), _data) // Increment buffer length - 0x60 plus the original length mstore(ptr, add(0x60, mload(ptr))) } // Increment EMITS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of events pushed to buffer - mstore(0x140, add(1, mload(0x140))) } // Update free memory pointer setFreeMem(); } function log(bytes32[1] memory _topics, bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push 1 to the end of the buffer - event will have 1 topic mstore(add(0x20, add(ptr, mload(ptr))), 1) // Push topic to end of buffer mstore(add(0x40, add(ptr, mload(ptr))), mload(_topics)) // If _data is zero, set data size to 0 in buffer and push - if eq(_data, 0) { mstore(add(0x60, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x60 plus the original length mstore(ptr, add(0x60, mload(ptr))) } // If _data is not zero, set size to 0x20 and push to buffer - if iszero(eq(_data, 0)) { // Push data size (0x20) to the end of the buffer mstore(add(0x60, add(ptr, mload(ptr))), 0x20) // Push data to the end of the buffer mstore(add(0x80, add(ptr, mload(ptr))), _data) // Increment buffer length - 0x80 plus the original length mstore(ptr, add(0x80, mload(ptr))) } // Increment EMITS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of events pushed to buffer - mstore(0x140, add(1, mload(0x140))) } // Update free memory pointer setFreeMem(); } function log(bytes32[2] memory _topics, bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push 2 to the end of the buffer - event will have 2 topics mstore(add(0x20, add(ptr, mload(ptr))), 2) // Push topics to end of buffer mstore(add(0x40, add(ptr, mload(ptr))), mload(_topics)) mstore(add(0x60, add(ptr, mload(ptr))), mload(add(0x20, _topics))) // If _data is zero, set data size to 0 in buffer and push - if eq(_data, 0) { mstore(add(0x80, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x80 plus the original length mstore(ptr, add(0x80, mload(ptr))) } // If _data is not zero, set size to 0x20 and push to buffer - if iszero(eq(_data, 0)) { // Push data size (0x20) to the end of the buffer mstore(add(0x80, add(ptr, mload(ptr))), 0x20) // Push data to the end of the buffer mstore(add(0xa0, add(ptr, mload(ptr))), _data) // Increment buffer length - 0xa0 plus the original length mstore(ptr, add(0xa0, mload(ptr))) } // Increment EMITS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of events pushed to buffer - mstore(0x140, add(1, mload(0x140))) } // Update free memory pointer setFreeMem(); } function log(bytes32[3] memory _topics, bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push 3 to the end of the buffer - event will have 3 topics mstore(add(0x20, add(ptr, mload(ptr))), 3) // Push topics to end of buffer mstore(add(0x40, add(ptr, mload(ptr))), mload(_topics)) mstore(add(0x60, add(ptr, mload(ptr))), mload(add(0x20, _topics))) mstore(add(0x80, add(ptr, mload(ptr))), mload(add(0x40, _topics))) // If _data is zero, set data size to 0 in buffer and push - if eq(_data, 0) { mstore(add(0xa0, add(ptr, mload(ptr))), 0) // Increment buffer length - 0xa0 plus the original length mstore(ptr, add(0xa0, mload(ptr))) } // If _data is not zero, set size to 0x20 and push to buffer - if iszero(eq(_data, 0)) { // Push data size (0x20) to the end of the buffer mstore(add(0xa0, add(ptr, mload(ptr))), 0x20) // Push data to the end of the buffer mstore(add(0xc0, add(ptr, mload(ptr))), _data) // Increment buffer length - 0xc0 plus the original length mstore(ptr, add(0xc0, mload(ptr))) } // Increment EMITS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of events pushed to buffer - mstore(0x140, add(1, mload(0x140))) } // Update free memory pointer setFreeMem(); } function log(bytes32[4] memory _topics, bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push 4 to the end of the buffer - event will have 4 topics mstore(add(0x20, add(ptr, mload(ptr))), 4) // Push topics to end of buffer mstore(add(0x40, add(ptr, mload(ptr))), mload(_topics)) mstore(add(0x60, add(ptr, mload(ptr))), mload(add(0x20, _topics))) mstore(add(0x80, add(ptr, mload(ptr))), mload(add(0x40, _topics))) mstore(add(0xa0, add(ptr, mload(ptr))), mload(add(0x60, _topics))) // If _data is zero, set data size to 0 in buffer and push - if eq(_data, 0) { mstore(add(0xc0, add(ptr, mload(ptr))), 0) // Increment buffer length - 0xc0 plus the original length mstore(ptr, add(0xc0, mload(ptr))) } // If _data is not zero, set size to 0x20 and push to buffer - if iszero(eq(_data, 0)) { // Push data size (0x20) to the end of the buffer mstore(add(0xc0, add(ptr, mload(ptr))), 0x20) // Push data to the end of the buffer mstore(add(0xe0, add(ptr, mload(ptr))), _data) // Increment buffer length - 0xe0 plus the original length mstore(ptr, add(0xe0, mload(ptr))) } // Increment EMITS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of events pushed to buffer - mstore(0x140, add(1, mload(0x140))) } // Update free memory pointer setFreeMem(); } // Begins creating a storage buffer - destinations entered will be forwarded wei // before the end of execution function paying() conditions(validPayBuff, isPaying) internal pure { bytes4 action_req = PAYS; assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push requestor to the end of buffer, as well as to the 'current action' slot - mstore(add(0x20, add(ptr, mload(ptr))), action_req) // Push '0' to the end of the 4 bytes just pushed - this will be the length of the PAYS action mstore(add(0x24, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x24 plus the previous length mstore(ptr, add(0x24, mload(ptr))) // Set the current action being executed (PAYS) - mstore(0xe0, action_req) // Set the expected next function - PAY_AMT mstore(0x100, 8) // Set a pointer to the length of the current request within the buffer mstore(sub(ptr, 0x20), add(ptr, mload(ptr))) } // Update free memory pointer setFreeMem(); } // Pushes an amount of wei to forward to the buffer function pay(uint _amount) conditions(validPayAmt, validPayDest) internal pure returns (uint) { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push payment amount to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _amount) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - PAY_DEST mstore(0x100, 7) // Increment PAYS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of payment destinations to be pushed to - mstore(0x160, add(1, mload(0x160))) } // Update free memory pointer setFreeMem(); return _amount; } // Push an address to forward wei to, to the buffer function toAcc(uint, address _dest) conditions(validPayDest, validPayAmt) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push payment destination to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _dest) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - PAY_AMT mstore(0x100, 8) } // Update free memory pointer setFreeMem(); } // Sets the free memory pointer to point beyond all accessed memory function setFreeMem() private pure { assembly { mstore(0x40, msize) } } // Returns the enum representing the next expected function to be called - function expected() private pure returns (NextFunction next) { assembly { next := mload(0x100) } } // Returns the number of events pushed to the storage buffer - function emitted() internal pure returns (uint num_emitted) { if (buffPtr() == bytes32(0)) return 0; // Load number emitted from buffer - assembly { num_emitted := mload(0x140) } } // Returns the number of storage slots pushed to the storage buffer - function stored() internal pure returns (uint num_stored) { if (buffPtr() == bytes32(0)) return 0; // Load number stored from buffer - assembly { num_stored := mload(0x120) } } // Returns the number of payment destinations and amounts pushed to the storage buffer - function paid() internal pure returns (uint num_paid) { if (buffPtr() == bytes32(0)) return 0; // Load number paid from buffer - assembly { num_paid := mload(0x160) } } } library Transfer { using Contract for *; // 'Transfer' event topic signature bytes32 private constant TRANSFER_SIG = keccak256('Transfer(address,address,uint256)'); // Returns the topics for a Transfer event - function TRANSFER (address _owner, address _dest) private pure returns (bytes32[3] memory) { return [TRANSFER_SIG, bytes32(_owner), bytes32(_dest)]; } // Ensures the sender is a transfer agent, or that the tokens are unlocked function canTransfer() internal view { if ( Contract.read(Token.transferAgents(Contract.sender())) == 0 && Contract.read(Token.isFinished()) == 0 ) revert('transfers are locked'); } // Implements the logic for a token transfer - function transfer(address _dest, uint _amt) internal view { // Ensure valid input - if (_dest == 0 || _dest == Contract.sender()) revert('invalid recipient'); // Ensure the sender can currently transfer tokens Contract.checks(canTransfer); // Begin updating balances - Contract.storing(); // Update sender token balance - reverts in case of underflow Contract.decrease(Token.balances(Contract.sender())).by(_amt); // Update recipient token balance - reverts in case of overflow Contract.increase(Token.balances(_dest)).by(_amt); // Finish updating balances: log event - Contract.emitting(); // Log 'Transfer' event Contract.log( TRANSFER(Contract.sender(), _dest), bytes32(_amt) ); } // Implements the logic for a token transferFrom - function transferFrom(address _owner, address _dest, uint _amt) internal view { // Ensure valid input - if (_dest == 0 || _dest == _owner) revert('invalid recipient'); if (_owner == 0) revert('invalid owner'); // Owner must be able to transfer tokens - if ( Contract.read(Token.transferAgents(_owner)) == 0 && Contract.read(Token.isFinished()) == 0 ) revert('transfers are locked'); // Begin updating balances - Contract.storing(); // Update spender token allowance - reverts in case of underflow Contract.decrease(Token.allowed(_owner, Contract.sender())).by(_amt); // Update owner token balance - reverts in case of underflow Contract.decrease(Token.balances(_owner)).by(_amt); // Update recipient token balance - reverts in case of overflow Contract.increase(Token.balances(_dest)).by(_amt); // Finish updating balances: log event - Contract.emitting(); // Log 'Transfer' event Contract.log( TRANSFER(_owner, _dest), bytes32(_amt) ); } } library Approve { using Contract for *; // event Approval(address indexed owner, address indexed spender, uint tokens) bytes32 internal constant APPROVAL_SIG = keccak256('Approval(address,address,uint256)'); // Returns the events and data for an 'Approval' event - function APPROVAL (address _owner, address _spender) private pure returns (bytes32[3] memory) { return [APPROVAL_SIG, bytes32(_owner), bytes32(_spender)]; } // Implements the logic to create the storage buffer for a Token Approval function approve(address _spender, uint _amt) internal pure { // Begin storing values - Contract.storing(); // Store the approved amount at the sender's allowance location for the _spender Contract.set(Token.allowed(Contract.sender(), _spender)).to(_amt); // Finish storing, and begin logging events - Contract.emitting(); // Log 'Approval' event - Contract.log( APPROVAL(Contract.sender(), _spender), bytes32(_amt) ); } // Implements the logic to create the storage buffer for a Token Approval function increaseApproval(address _spender, uint _amt) internal view { // Begin storing values - Contract.storing(); // Store the approved amount at the sender's allowance location for the _spender Contract.increase(Token.allowed(Contract.sender(), _spender)).by(_amt); // Finish storing, and begin logging events - Contract.emitting(); // Log 'Approval' event - Contract.log( APPROVAL(Contract.sender(), _spender), bytes32(_amt) ); } // Implements the logic to create the storage buffer for a Token Approval function decreaseApproval(address _spender, uint _amt) internal view { // Begin storing values - Contract.storing(); // Decrease the spender's approval by _amt to a minimum of 0 - Contract.decrease(Token.allowed(Contract.sender(), _spender)).byMaximum(_amt); // Finish storing, and begin logging events - Contract.emitting(); // Log 'Approval' event - Contract.log( APPROVAL(Contract.sender(), _spender), bytes32(_amt) ); } } library Token { using Contract for *; /// SALE /// // Whether or not the crowdsale is post-purchase function isFinished() internal pure returns (bytes32) { return keccak256("sale_is_completed"); } /// TOKEN /// // Storage location for token name function tokenName() internal pure returns (bytes32) { return keccak256("token_name"); } // Storage seed for user balances mapping bytes32 internal constant TOKEN_BALANCES = keccak256("token_balances"); function balances(address _owner) internal pure returns (bytes32) { return keccak256(_owner, TOKEN_BALANCES); } // Storage seed for user allowances mapping bytes32 internal constant TOKEN_ALLOWANCES = keccak256("token_allowances"); function allowed(address _owner, address _spender) internal pure returns (bytes32) { return keccak256(_spender, keccak256(_owner, TOKEN_ALLOWANCES)); } // Storage seed for token 'transfer agent' status for any address // Transfer agents can transfer tokens, even if the crowdsale has not yet been finalized bytes32 internal constant TOKEN_TRANSFER_AGENTS = keccak256("token_transfer_agents"); function transferAgents(address _agent) internal pure returns (bytes32) { return keccak256(_agent, TOKEN_TRANSFER_AGENTS); } /// CHECKS /// // Ensures the sale's token has been initialized function tokenInit() internal view { if (Contract.read(tokenName()) == 0) revert('token not initialized'); } // Ensures both storage and events have been pushed to the buffer function emitAndStore() internal pure { if (Contract.emitted() == 0 || Contract.stored() == 0) revert('invalid state change'); } /// FUNCTIONS /// /* Allows a token holder to transfer tokens to another address @param _to: The destination that will recieve tokens @param _amount: The number of tokens to transfer */ function transfer(address _to, uint _amount) external view { // Begin execution - reads execution id and original sender address from storage Contract.authorize(msg.sender); // Check that the token is initialized - Contract.checks(tokenInit); // Execute transfer function - Transfer.transfer(_to, _amount); // Ensures state change will affect storage and events - Contract.checks(emitAndStore); // Commit state changes to storage - Contract.commit(); } /* Allows an approved spender to transfer tokens to another address on an owner's behalf @param _owner: The address from which tokens will be sent @param _recipient: The destination to which tokens will be sent @param _amount: The number of tokens to transfer */ function transferFrom(address _owner, address _recipient, uint _amount) external view { // Begin execution - reads execution id and original sender address from storage Contract.authorize(msg.sender); // Check that the token is initialized - Contract.checks(tokenInit); // Execute transfer function - Transfer.transferFrom(_owner, _recipient, _amount); // Ensures state change will affect storage and events - Contract.checks(emitAndStore); // Commit state changes to storage - Contract.commit(); } /* Approves a spender to spend an amount of your tokens on your behalf @param _spender: The address allowed to spend your tokens @param _amount: The number of tokens that will be approved */ function approve(address _spender, uint _amount) external view { // Begin execution - reads execution id and original sender address from storage Contract.authorize(msg.sender); // Check that the token is initialized - Contract.checks(tokenInit); // Execute approval function - Approve.approve(_spender, _amount); // Ensures state change will affect storage and events - Contract.checks(emitAndStore); // Commit state changes to storage - Contract.commit(); } /* Increases a spender's approval amount @param _spender: The address allowed to spend your tokens @param _amount: The amount by which the spender's allowance will be increased */ function increaseApproval(address _spender, uint _amount) external view { // Begin execution - reads execution id and original sender address from storage Contract.authorize(msg.sender); // Check that the token is initialized - Contract.checks(tokenInit); // Execute approval function - Approve.increaseApproval(_spender, _amount); // Ensures state change will affect storage and events - Contract.checks(emitAndStore); // Commit state changes to storage - Contract.commit(); } /* Decreases a spender's approval amount @param _spender: The address allowed to spend your tokens @param _amount: The amount by which the spender's allowance will be decreased */ function decreaseApproval(address _spender, uint _amount) external view { // Begin execution - reads execution id and original sender address from storage Contract.authorize(msg.sender); // Check that the token is initialized - Contract.checks(tokenInit); // Execute approval function - Approve.decreaseApproval(_spender, _amount); // Ensures state change will affect storage and events - Contract.checks(emitAndStore); // Commit state changes to storage - Contract.commit(); } }
Checks that a call pushing a storage value to the buffer is expected and valid Ensure that the next function expected pushes a storage value - Ensure that the current buffer is pushing STORES actions -
function validStoreVal() private pure { if ( expected() != NextFunction.VAL_SET && expected() != NextFunction.VAL_INC && expected() != NextFunction.VAL_DEC ) revert('Unexpected function order - expected storage value to be pushed'); isStoring(); }
1,484,855
./partial_match/1/0xFB41B505b83D3fF7FdbeE5527C744C7fdb975026/sources/COOL.sol
remove limits after token is stable
function removeLimits() external onlyOwner { limitsInEffect = false; buyFee = 1; sellFee = 1; }
2,721,102
./partial_match/42220/0xe6F77e6c1Df6Aea40923659C0415d82119F34882/sources/home/eruiz/Projects/celo/celo-monorepo/packages/protocol/contracts/governance/Proposals.sol
Constructs a proposal. proposal The proposal struct to be constructed. values The values of CELO to be sent in the proposed transactions. destinations The destination addresses of the proposed transactions. data The concatenated data to be included in the proposed transactions. dataLengths The lengths of each transaction's data. proposer The proposer. deposit The proposal deposit./ solhint-disable-next-line not-rely-on-time
function make( Proposal storage proposal, uint256[] memory values, address[] memory destinations, bytes memory data, uint256[] memory dataLengths, address proposer, uint256 deposit ) public { require( values.length == destinations.length && destinations.length == dataLengths.length, "Array length mismatch" ); uint256 transactionCount = values.length; proposal.proposer = proposer; proposal.deposit = deposit; proposal.timestamp = now; uint256 dataPosition = 0; delete proposal.transactions; for (uint256 i = 0; i < transactionCount; i = i.add(1)) { proposal.transactions.push( Transaction(values[i], destinations[i], data.slice(dataPosition, dataLengths[i])) ); dataPosition = dataPosition.add(dataLengths[i]); } }
3,498,754
./full_match/3/0xf6b62Ef67fc2A7d122e08cbde38BDE08Ad5aAE50/sources/releasable__1__mod.sol
Transfers manager permissions to a new account (`newManager`). Internal function without access restriction./
function _setManager(address newManager) internal { address oldManager = _manager; _manager = newManager; emit ManagementTransferred(oldManager, newManager); }
8,148,305
pragma solidity ^0.4.10; /// @title A group expenses smart contract allowing you to settle up your debts and credits /// @author Adrien Arcuri /// @notice You can use this contract to record your group expenses, Payment participants, /// check the debts and credits of the groups and settle up. /// @dev No comments for dev contract WeExpenses { /** Participant is a person or an organization which is part of the group expense. */ struct Participant { string name; address waddress; int balance; uint index; } /** Expense is cost incurred which will be pay back. Expense has an impact on the balance for payer and payee only if payee give its agreement. */ struct Expense { string title; uint amount; uint valueDate; uint creationDate; address payer; address[] payees; mapping(address => bool) agreements; } /** Payment is money transfer from one participant to another. Payment can be use to settle a debt or a credit. */ struct Payment { string title; uint amount; uint valueDate; address payer; address payee; } /// This declares a state variable that stores a `Participant` struct for each possible address. mapping(address => Participant) public participants; /// This store in an array all the participants address[] public addressList; /// Allow the creation of the first participant when the contract is deployed bool public deployed = false; // A dynamically-sized array of `Expenses` structs. Expense[] public expenses; // A dynamically-sized array of `Payments` structs. Payment[] public payments; // A mapping of all the available withdrawals per address mapping(address => uint) public withdrawals; /// This modifier requires that the sender of the transaction is registred as participant modifier onlyByParticipant () { require(msg.sender == participants[msg.sender].waddress || !deployed); _; } /// @notice Constructor of our smart contract. The creator of the smart contract will be the first participant. /// @dev /// @param name the name of the first participant /// @return function WeExpenses(string name) public { createParticipant(name, msg.sender); deployed = true; } /// @notice Create a participant. Only registered participant can add new participant /// @param _name the name of the participant /// @param _waddress the address of the participant function createParticipant(string _name, address _waddress) public onlyByParticipant() { require(_waddress != participants[_waddress].waddress || !deployed); //only one address per participant require(_waddress != address(0)); // avoid to participant address equal to 0x0 Participant memory participant = Participant({name: _name, waddress: _waddress, balance: 0, index: 0}); participant.index = addressList.push(_waddress)-1; //add the address to the addressList participants[_waddress] = participant; } /// @notice Create an expense as payer. By default, the payer is the creator of the expense /// @dev The number of payees are limited to 20 to avoid gas limit using loop /// @param _title the title of the expense /// @param _amount the amount of the expense. Must be superior to zero /// @param _valueDate the value date of the expense /// @param _payees the list of payee of the expense. The payer can be part of the payees function createExpense(string _title, uint _amount, uint _valueDate, address[] _payees) public onlyByParticipant() { address _payer = msg.sender; require(_amount > 0); require(_payees.length > 0 && _payees.length <= 20); require(isParticipant(_payer)); require(isParticipants(_payees)); require(!isDuplicateInpayees(_payees)); Expense memory expense = Expense(_title, _amount, _valueDate, now, _payer, _payees); expenses.push(expense); } /// @notice Set participant's agreeement for an expense. Each participant has 4 weeks to set its agreement. /// @param indexExpense the index of the expense /// @param agree the agreement of the participant : true of false function setAgreement(uint indexExpense, bool agree) public onlyByParticipant() { Expense storage expense = expenses[indexExpense]; require(now < expense.creationDate + 4 weeks); require(expense.agreements[msg.sender] != agree); uint numberOfAgreeBefore = getNumberOfAgreements(indexExpense); /// Warning : There is no agreements when the expense is created. That's mean the balance did not synchronize. /// If the number of agreements before is not 0, we revert the balance to the previous state without the expense if (numberOfAgreeBefore != 0) { revertBalance(indexExpense); } /// Update the number of agreements expense.agreements[msg.sender] = agree; uint numberOfAgreeAfter = getNumberOfAgreements(indexExpense); /// If the number of agreements after is not 0, we syncrhonize the balance if (numberOfAgreeAfter != 0) { syncBalance(indexExpense); } } /// @notice Create a Payment. Use this payable function send money to the smart contract. /// @param _title the title of the payment /// @param _payee the payee of the payment function createPayment(string _title, address _payee) public onlyByParticipant() payable { address _payer = msg.sender; require(msg.value > 0); require(_payee != _payer); require(isParticipant(_payer)); require(isParticipant(_payee)); Payment memory payment = Payment({title: _title, amount: msg.value, valueDate: now, payer: _payer, payee: _payee}); payments.push(payment); withdrawals[_payee] += msg.value; syncBalancePayment(payment); } /// @notice Allow each user to withdraw its money from the smart contract function withdraw() public onlyByParticipant() { require(withdrawals[msg.sender] > 0); uint amount = withdrawals[msg.sender]; withdrawals[msg.sender] = 0; msg.sender.transfer(amount); } /// @notice Get the max of all balances /// @return (max, index) where max is the max of all the balance and index is the index of the participant function getMaxBalance() public view returns (int, uint) { int max = participants[addressList[0]].balance; uint index = 0; for (uint i = 1; i < addressList.length; i++) { if (max != max256(max, participants[addressList[i]].balance)) { max = participants[addressList[i]].balance; index = i; } } return (max, index); } /// @notice Get withdrawal per address /// @return the available withdrawal for the waddress function getWithdrawal(address waddress) public view returns (uint) { return withdrawals[waddress]; } /// @notice Get agreement depending on the indexExpenses and address of the participant /// @param indexExpense the index of the expense /// @param _waddress address of the payee /// @return true if payee gave is agreement, else false function getAgreement(uint indexExpense, address _waddress) public view returns (bool) { return expenses[indexExpense].agreements[_waddress]; } /// @notice Get the total number of agreements for a given expense /// @param indexExpense the index of the expense /// @return the number of agreements function getNumberOfAgreements(uint indexExpense) public view returns (uint) { Expense storage expense = expenses[indexExpense]; uint numberOfAgreements = 0; for (uint i = 0; i < expense.payees.length; i++) { if (expense.agreements[expense.payees[i]] == true) { numberOfAgreements++; } } return numberOfAgreements; } /// @notice Get balance of a participant /// @param _waddress the address of the participant /// @return the balance of the participant function getBalance(address _waddress) public view returns (int) { return participants[_waddress].balance; } /// @notice Get name of a participant /// @param _waddress the address of the participant /// @return the name of the participant function getParticipantName(address _waddress) public view returns (string) { return participants[_waddress].name; } /// @notice Check if there is duplicate inside array /// @param list the list of address to check /// @return true if there is duplicate, false otherwise function isDuplicateInpayees(address[] list) internal pure returns (bool) { uint counter; for (uint i = 0; i < list.length; i++) { counter = 0; address addr = list[i]; for (uint j = 0; j < list.length; j++) { if (addr == list[j]) {counter++;} if (counter == 2) {return true;} } } return false; } /// @notice Check if each address of the list is registred as participant /// @param list the list of address to check /// @return true if all the list is registred as participant, false otherwise function isParticipants(address[] list) internal view returns (bool) { for (uint i = 0; i < list.length; i++) { if (!isParticipant(list[i])) { return false; } } return true; } /// @notice Check if each address of the list is registred as participant /// @param _waddress the address to check /// @return true if all the list is registred as participant, false otherwise function isParticipant(address _waddress) internal view returns (bool) { if (_waddress == participants[_waddress].waddress) { return true; }else { return false; } } /// @notice synchronize balance after each change of the agreements state /// @dev This function must be use if there is at list one agreement in the expense /// @param indexExpense the index of the expense function syncBalance(uint indexExpense) internal { calculateBalance(indexExpense, false); } /// @notice Revert the state of the balance after each change of the agreements state /// @dev This function must not be use if there is zero agreement /// @param indexExpense the index of the expense function revertBalance(uint indexExpense) internal { calculateBalance(indexExpense, true); } /// @notice Calculate the state of the balance after each change of the agreements state (revert or synchornize) /// @param indexExpense the index of the expense /// @param isRevert indicate if the expense must be reverted or synchronized function calculateBalance(uint indexExpense, bool isRevert) internal { uint contributors = getNumberOfAgreements(indexExpense); require(contributors > 0); Expense storage expense = expenses[indexExpense]; int _portion = int(expense.amount / contributors); int _amount = int(expense.amount); if (isRevert) { _portion = -(_portion); _amount = -(_amount); } participants[expense.payer].balance += _amount; for (uint i = 0; i < expense.payees.length; i++) { if (expense.agreements[expense.payees[i]]) { participants[expense.payees[i]].balance -= _portion; } } } /// @notice Calculate the state of the balance after each new payement /// @param payment which will alter balance function syncBalancePayment(Payment payment) internal { participants[payment.payee].balance -= int(payment.amount); participants[payment.payer].balance += int(payment.amount); } function max256(int256 a, int256 b) internal pure returns (int256) { return a >= b ? a : b; } function min256(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } }
Constructor of our smart contract. The creator of the smart contract will be the first participant. name the name of the first participant return
function WeExpenses(string name) public { createParticipant(name, msg.sender); deployed = true; }
14,106,474
./partial_match/97/0x7F5267Ac54dFFB7577139CfB118C867b567060DA/sources/HRPToken.sol
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "HRP::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
11,411,504
./full_match/1/0x9f48313C86249A8A369c830cE0379cb634B94935/sources/browser/Farming/FarmManager.sol
fund a farm with amount. must give allowance to created farm first.
function fund(uint _fid, uint256 _amount) public { require(funders[msg.sender] == true, "fund: sender is not funder"); farms[_fid].fund(_amount); }
2,916,494
pragma ton-solidity ^0.37.0; pragma AbiHeader expire; pragma AbiHeader time; pragma AbiHeader pubkey; import "./interfaces/IRootAuction.sol"; import "./interfaces/IAuction.sol"; /** * Error codes * 100 - Method for the root only * 101 - Invalid number of periods * 102 - Bid period is over * 103 - Submitting period is over * 104 - Finish period is over * 105 - Value is zero * 106 - Invalid hash * 107 - Invalid hash sender */ contract Auction is IAuction { /************* * STRUCTURES * *************/ struct Winner { address addr; uint128 value; } /********** * STATIC * **********/ string static _name; address static _root; /************* * VARIABLES * *************/ uint32 private _bidsDuration; uint32 private _submittingDuration; uint32 private _finishDuration; bool private _finished; uint8 private _periods; uint32 private _bidsEndTime; uint32 private _submittingEndTime; uint32 private _finishTime; bool private _needToCreate; mapping(uint256 => address) private _bids; Winner private _first; Winner private _second; /************* * MODIFIERS * *************/ modifier accept { tvm.accept(); _; } modifier onlyRoot() { require(msg.sender == _root, 100, "Method for the root only"); _; } modifier periodsAreQqual(uint8 periods) { require(periods == _periods, 101, "Invalid number of periods"); _; } modifier canBid() { require(now < _bidsEndTime, 102, "Bid period is over"); _; } modifier canSubmit() { require(now >= _bidsEndTime && now < _submittingEndTime, 103, "Submitting period is over"); _; } modifier canFinish() { require(!_finished && now >= _submittingEndTime && now < _finishTime, 104, "Finish period is over"); _; } modifier notZeroValue() { require(msg.value > 0, 105, "Value is zero"); _; } modifier hashExists(uint256 hash) { require(_bids.exists(hash), 106, "Invalid hash"); _; } modifier hashSenderIsValid(address sender, uint256 hash) { require(_bids[hash] == sender, 107, "Invalid hash sender"); _; } /*************************** * CONSTRUCTOR * ONLY ROOT * ***************************/ /** * bidsDuration ....... The minimum duration of the auction in seconds. * submittingDuration . Duration of period, in seconds, during which users can pay value. * finishDuration ..... Duration of period, in seconds, during which users can complete auction. */ constructor(uint32 bidsDuration, uint32 submittingDuration, uint32 finishDuration) public onlyRoot accept { _bidsDuration = bidsDuration; _submittingDuration = submittingDuration; _finishDuration = finishDuration; } /************************ * EXTERNAL * ONLY ROOT * ************************/ function bid(address sender, uint8 periods, uint256 hash, bool needToCreate) external onlyRoot { /////////////////////////////////////////////////////////////////// // Restart if auction finished by user or time to finish is over // /////////////////////////////////////////////////////////////////// if (_finished || (_finishTime < now)) _restartAuction(sender, periods, hash, needToCreate); else _bid(sender, periods, hash); } /********** * PUBLIC * **********/ ////////////////////////////////////////////////////////// // Participants confirm the bid with money. // // If make it possible not to confirm the bid with // // money, then the trolls will be able to do this: // // // // 1. Bet on 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF // // 2. Win the auction. // // 3. Don't pay. // // // // This makes it possible for anyone who wants to block // // any auction for just 1 crystal. It is unacceptable. // ////////////////////////////////////////////////////////// function submit(uint256 salt) public canSubmit notZeroValue { address sender = msg.sender; uint128 value = msg.value; TvmBuilder builder; builder.store(value); builder.store(salt); TvmCell cell = builder.toCell(); uint256 bidHash = tvm.hash(cell); _submit(sender, value, bidHash); } ////////////////////////////////////////////////////// // Anyone can finish auction if the auction has not // // finished yet and the finishing time has come. // ////////////////////////////////////////////////////// function finish() public canFinish { Winner first = _first; Winner second = _second; _sendGrams(second.addr, second.value); _sendGrams(first.addr, first.value - second.value); _finished = true; IRootAuction(_root).auctionComplete{value: 0, flag: 128}( _name, _periods, first.addr, second.value, _needToCreate ); } /*********** * GETTERS * ***********/ function getInfo() override public view returns( bool finished, uint8 periods, uint32 bidsEndTime, uint32 submittingEndTime, uint32 finishTime, address firstWinnerAddress, uint128 firstWinnerValue, address secondWinnerAddress, uint128 secondWinnerValue ) { return ( _finished, _periods, _bidsEndTime, _submittingEndTime, _finishTime, _first.addr, _first.value, _second.addr, _second.value ); } /*********** * PRIVATE * **********/ function _restartAuction(address sender, uint8 periods, uint256 hash, bool needToCreate) private { _finished = false; _periods = periods; _bidsEndTime = now + _periods * _bidsDuration; _submittingEndTime = _bidsEndTime + _submittingDuration; _finishTime = _submittingEndTime + _finishDuration; _needToCreate = needToCreate; _bids.add(hash, sender); _first = Winner(address(0), 0); _second = Winner(address(0), 0); } function _bid( address sender, uint8 periods, uint256 hash ) private periodsAreQqual(periods) canBid { _bids.add(hash, sender); } ////////////////////////////////////////////////////////// // Participants who did not take the first two places // // receive their bets back. Participants who finish in // // the first two places receive money when the finish() // // is called. // ////////////////////////////////////////////////////////// function _submit(address sender, uint128 value, uint256 hash) private hashExists(hash) hashSenderIsValid(sender, hash) { delete _bids[hash]; Winner first = _first; Winner second = _second; Winner newbie = Winner(sender, value); if (value > first.value) { _first = newbie; _second = first; _sendGrams(second.addr, second.value); } else if (value > first.value) { _second = Winner(sender, value); _sendGrams(second.addr, second.value); } else _sendGrams(newbie.addr, newbie.value); if (_bids.empty()) finish(); } function _sendGrams(address addr, uint128 value) private pure { if (value > 0) address(addr).transfer(value, false); } }
PUBLIC // Participants confirm the bid with money. If make it possible not to confirm the bid with money, then the trolls will be able to do this: 1. Bet on 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF 2. Win the auction. 3. Don't pay. This makes it possible for anyone who wants to block any auction for just 1 crystal. It is unacceptable. /
function submit(uint256 salt) public canSubmit notZeroValue { address sender = msg.sender; uint128 value = msg.value; TvmBuilder builder; builder.store(value); builder.store(salt); TvmCell cell = builder.toCell(); uint256 bidHash = tvm.hash(cell); _submit(sender, value, bidHash); }
13,031,120
./full_match/44787/0x33F8d23a573544a9D80B74c029a3aB392aEDB40A/sources/contracts/StarFarm.sol
Deposit LP tokens to MasterChef for STAR allocation.
function deposit(uint256 _pid, uint256 _amount) public { if (_pid == 0) require(userNFTs[_msgSender()].length == 0, "nft user"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_msgSender()]; updatePool(_pid); (uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(); uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100)); if (_amountGain > 0) { uint256 pending = _amountGain.mul(pool.accStarPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { if (user.lastDeposit > block.timestamp.sub(604800)) { pending = pending.mul(90).div(100); starToken.safeTransfer(bonusAddr, pending.mul(10).div(100)); } starToken.safeTransfer(_msgSender(), pending); starNode.settleNode(_msgSender(), user.amount); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount); user.amount = user.amount.add(_amount); uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100); pool.extraAmount = pool.extraAmount.add(_extraAmount); _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100)); } user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12); emit Deposit(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]); }
13,250,115
pragma solidity 0.5.17; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {TBTCDepositToken} from "./TBTCDepositToken.sol"; import {FeeRebateToken} from "./FeeRebateToken.sol"; import {TBTCToken} from "./TBTCToken.sol"; import {TBTCConstants} from "./TBTCConstants.sol"; import "../deposit/Deposit.sol"; import "./TBTCSystemAuthority.sol"; /// @title Vending Machine /// @notice The Vending Machine swaps TDTs (`TBTCDepositToken`) /// to TBTC (`TBTCToken`) and vice versa. /// @dev The Vending Machine should have exclusive TBTC and FRT (`FeeRebateToken`) minting /// privileges. contract VendingMachine is TBTCSystemAuthority{ using SafeMath for uint256; TBTCToken tbtcToken; TBTCDepositToken tbtcDepositToken; FeeRebateToken feeRebateToken; uint256 createdAt; constructor(address _systemAddress) TBTCSystemAuthority(_systemAddress) public { createdAt = block.timestamp; } /// @notice Set external contracts needed by the Vending Machine. /// @dev Addresses are used to update the local contract instance. /// @param _tbtcToken TBTCToken contract. More info in `TBTCToken`. /// @param _tbtcDepositToken TBTCDepositToken (TDT) contract. More info in `TBTCDepositToken`. /// @param _feeRebateToken FeeRebateToken (FRT) contract. More info in `FeeRebateToken`. function setExternalAddresses( TBTCToken _tbtcToken, TBTCDepositToken _tbtcDepositToken, FeeRebateToken _feeRebateToken ) external onlyTbtcSystem { tbtcToken = _tbtcToken; tbtcDepositToken = _tbtcDepositToken; feeRebateToken = _feeRebateToken; } /// @notice Burns TBTC and transfers the tBTC Deposit Token to the caller /// as long as it is qualified. /// @dev We burn the lotSize of the Deposit in order to maintain /// the TBTC supply peg in the Vending Machine. VendingMachine must be approved /// by the caller to burn the required amount. /// @param _tdtId ID of tBTC Deposit Token to buy. function tbtcToTdt(uint256 _tdtId) external { require(tbtcDepositToken.exists(_tdtId), "tBTC Deposit Token does not exist"); require(isQualified(address(_tdtId)), "Deposit must be qualified"); uint256 depositValue = Deposit(address(uint160(_tdtId))).lotSizeTbtc(); require(tbtcToken.balanceOf(msg.sender) >= depositValue, "Not enough TBTC for TDT exchange"); tbtcToken.burnFrom(msg.sender, depositValue); // TODO do we need the owner check below? transferFrom can be approved for a user, which might be an interesting use case. require(tbtcDepositToken.ownerOf(_tdtId) == address(this), "Deposit is locked"); tbtcDepositToken.transferFrom(address(this), msg.sender, _tdtId); } /// @notice Transfer the tBTC Deposit Token and mint TBTC. /// @dev Transfers TDT from caller to vending machine, and mints TBTC to caller. /// Vending Machine must be approved to transfer TDT by the caller. /// @param _tdtId ID of tBTC Deposit Token to sell. function tdtToTbtc(uint256 _tdtId) public { require(tbtcDepositToken.exists(_tdtId), "tBTC Deposit Token does not exist"); require(isQualified(address(_tdtId)), "Deposit must be qualified"); tbtcDepositToken.transferFrom(msg.sender, address(this), _tdtId); Deposit deposit = Deposit(address(uint160(_tdtId))); uint256 signerFee = deposit.signerFeeTbtc(); uint256 depositValue = deposit.lotSizeTbtc(); require(canMint(depositValue), "Can't mint more than the max supply cap"); // If the backing Deposit does not have a signer fee in escrow, mint it. if(tbtcToken.balanceOf(address(_tdtId)) < signerFee) { tbtcToken.mint(msg.sender, depositValue.sub(signerFee)); tbtcToken.mint(address(_tdtId), signerFee); } else{ tbtcToken.mint(msg.sender, depositValue); } // owner of the TDT during first TBTC mint receives the FRT if(!feeRebateToken.exists(_tdtId)){ feeRebateToken.mint(msg.sender, _tdtId); } } /// @notice Return whether an amount of TBTC can be minted according to the supply cap /// schedule /// @dev This function is also used by TBTCSystem to decide whether to allow a new deposit. /// @return True if the amount can be minted without hitting the max supply, false otherwise. function canMint(uint256 amount) public view returns (bool) { return getMintedSupply().add(amount) < getMaxSupply(); } /// @notice Determines whether a deposit is qualified for minting TBTC. /// @param _depositAddress The address of the deposit function isQualified(address payable _depositAddress) public view returns (bool) { return Deposit(_depositAddress).inActive(); } /// @notice Return the minted TBTC supply in weitoshis (BTC * 10 ** 18). function getMintedSupply() public view returns (uint256) { return tbtcToken.totalSupply(); } /// @notice Get the maximum TBTC token supply based on the age of the /// contract deployment. The supply cap starts at 2 BTC for the two /// days, 100 for the first week, 250 for the next, then 500, 750, /// 1000, 1500, 2000, 2500, and 3000... finally removing the minting /// restriction after 9 weeks and returning 21M BTC as a sanity /// check. /// @return The max supply in weitoshis (BTC * 10 ** 18). function getMaxSupply() public view returns (uint256) { uint256 age = block.timestamp - createdAt; if(age < 2 days) { return 2 * 10 ** 18; } if (age < 7 days) { return 100 * 10 ** 18; } if (age < 14 days) { return 250 * 10 ** 18; } if (age < 21 days) { return 500 * 10 ** 18; } if (age < 28 days) { return 750 * 10 ** 18; } if (age < 35 days) { return 1000 * 10 ** 18; } if (age < 42 days) { return 1500 * 10 ** 18; } if (age < 49 days) { return 2000 * 10 ** 18; } if (age < 56 days) { return 2500 * 10 ** 18; } if (age < 63 days) { return 3000 * 10 ** 18; } return 21e6 * 10 ** 18; } // WRAPPERS /// @notice Qualifies a deposit and mints TBTC. /// @dev User must allow VendingManchine to transfer TDT. function unqualifiedDepositToTbtc( address payable _depositAddress, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters Deposit _d = Deposit(_depositAddress); _d.provideBTCFundingProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); tdtToTbtc(uint256(_depositAddress)); } /// @notice Redeems a Deposit by purchasing a TDT with TBTC for _finalRecipient, /// and using the TDT to redeem corresponding Deposit as _finalRecipient. /// This function will revert if the Deposit is not in ACTIVE state. /// @dev Vending Machine transfers TBTC allowance to Deposit. /// @param _depositAddress The address of the Deposit to redeem. /// @param _outputValueBytes The 8-byte Bitcoin transaction output size in Little Endian. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. function tbtcToBtc( address payable _depositAddress, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters require(tbtcDepositToken.exists(uint256(_depositAddress)), "tBTC Deposit Token does not exist"); Deposit _d = Deposit(_depositAddress); tbtcToken.burnFrom(msg.sender, _d.lotSizeTbtc()); tbtcDepositToken.approve(_depositAddress, uint256(_depositAddress)); uint256 tbtcOwed = _d.getOwnerRedemptionTbtcRequirement(msg.sender); if(tbtcOwed != 0){ tbtcToken.transferFrom(msg.sender, address(this), tbtcOwed); tbtcToken.approve(_depositAddress, tbtcOwed); } _d.transferAndRequestRedemption(_outputValueBytes, _redeemerOutputScript, msg.sender); } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity 0.5.17; /** * @title Keep interface */ interface ITBTCSystem { // expected behavior: // return the price of 1 sat in wei // these are the native units of the deposit contract function fetchBitcoinPrice() external view returns (uint256); // passthrough requests for the oracle function fetchRelayCurrentDifficulty() external view returns (uint256); function fetchRelayPreviousDifficulty() external view returns (uint256); function getNewDepositFeeEstimate() external view returns (uint256); function getAllowNewDeposits() external view returns (bool); function isAllowedLotSize(uint64 _requestedLotSizeSatoshis) external view returns (bool); function requestNewKeep(uint64 _requestedLotSizeSatoshis, uint256 _maxSecuredLifetime) external payable returns (address); function getSignerFeeDivisor() external view returns (uint16); function getInitialCollateralizedPercent() external view returns (uint16); function getUndercollateralizedThresholdPercent() external view returns (uint16); function getSeverelyUndercollateralizedThresholdPercent() external view returns (uint16); } pragma solidity 0.5.17; import {DepositLiquidation} from "./DepositLiquidation.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositFunding} from "./DepositFunding.sol"; import {DepositRedemption} from "./DepositRedemption.sol"; import {DepositStates} from "./DepositStates.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {FeeRebateToken} from "../system/FeeRebateToken.sol"; import "../system/DepositFactoryAuthority.sol"; // solium-disable function-order // Below, a few functions must be public to allow bytes memory parameters, but // their being so triggers errors because public functions should be grouped // below external functions. Since these would be external if it were possible, // we ignore the issue. /// @title tBTC Deposit /// @notice This is the main contract for tBTC. It is the state machine that /// (through various libraries) handles bitcoin funding, bitcoin-spv /// proofs, redemption, liquidation, and fraud logic. /// @dev This contract presents a public API that exposes the following /// libraries: /// /// - `DepositFunding` /// - `DepositLiquidaton` /// - `DepositRedemption`, /// - `DepositStates` /// - `DepositUtils` /// - `OutsourceDepositLogging` /// - `TBTCConstants` /// /// Where these libraries require deposit state, this contract's state /// variable `self` is used. `self` is a struct of type /// `DepositUtils.Deposit` that contains all aspects of the deposit state /// itself. contract Deposit is DepositFactoryAuthority { using DepositRedemption for DepositUtils.Deposit; using DepositFunding for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; DepositUtils.Deposit self; /// @dev Deposit should only be _constructed_ once. New deposits are created /// using the `DepositFactory.createDeposit` method, and are clones of /// the constructed deposit. The factory will set the initial values /// for a new clone using `initializeDeposit`. constructor () public { // The constructed Deposit will never be used, so the deposit factory // address can be anything. Clones are updated as per above. initialize(address(0xdeadbeef)); } /// @notice Deposits do not accept arbitrary ETH. function () external payable { require(msg.data.length == 0, "Deposit contract was called with unknown function selector."); } //----------------------------- METADATA LOOKUP ------------------------------// /// @notice Get this deposit's BTC lot size in satoshis. /// @return uint64 lot size in satoshis. function lotSizeSatoshis() external view returns (uint64){ return self.lotSizeSatoshis; } /// @notice Get this deposit's lot size in TBTC. /// @dev This is the same as lotSizeSatoshis(), but is multiplied to scale /// to 18 decimal places. /// @return uint256 lot size in TBTC precision (max 18 decimal places). function lotSizeTbtc() external view returns (uint256){ return self.lotSizeTbtc(); } /// @notice Get the signer fee for this deposit, in TBTC. /// @dev This is the one-time fee required by the signers to perform the /// tasks needed to maintain a decentralized and trustless model for /// tBTC. It is a percentage of the deposit's lot size. /// @return Fee amount in TBTC. function signerFeeTbtc() external view returns (uint256) { return self.signerFeeTbtc(); } /// @notice Get the integer representing the current state. /// @dev We implement this because contracts don't handle foreign enums /// well. See `DepositStates` for more info on states. /// @return The 0-indexed state from the DepositStates enum. function currentState() external view returns (uint256) { return uint256(self.currentState); } /// @notice Check if the Deposit is in ACTIVE state. /// @return True if state is ACTIVE, false otherwise. function inActive() external view returns (bool) { return self.inActive(); } /// @notice Get the contract address of the BondedECDSAKeep associated with /// this Deposit. /// @dev The keep contract address is saved on Deposit initialization. /// @return Address of the Keep contract. function keepAddress() external view returns (address) { return self.keepAddress; } /// @notice Retrieve the remaining term of the deposit in seconds. /// @dev The value accuracy is not guaranteed since block.timestmap can be /// lightly manipulated by miners. /// @return The remaining term of the deposit in seconds. 0 if already at /// term. function remainingTerm() external view returns(uint256){ return self.remainingTerm(); } /// @notice Get the current collateralization level for this Deposit. /// @dev This value represents the percentage of the backing BTC value the /// signers currently must hold as bond. /// @return The current collateralization level for this deposit. function collateralizationPercentage() external view returns (uint256) { return self.collateralizationPercentage(); } /// @notice Get the initial collateralization level for this Deposit. /// @dev This value represents the percentage of the backing BTC value /// the signers hold initially. It is set at creation time. /// @return The initial collateralization level for this deposit. function initialCollateralizedPercent() external view returns (uint16) { return self.initialCollateralizedPercent; } /// @notice Get the undercollateralization level for this Deposit. /// @dev This collateralization level is semi-critical. If the /// collateralization level falls below this percentage the Deposit can /// be courtesy-called by calling `notifyCourtesyCall`. This value /// represents the percentage of the backing BTC value the signers must /// hold as bond in order to not be undercollateralized. It is set at /// creation time. Note that the value for new deposits in TBTCSystem /// can be changed by governance, but the value for a particular /// deposit is static once the deposit is created. /// @return The undercollateralized level for this deposit. function undercollateralizedThresholdPercent() external view returns (uint16) { return self.undercollateralizedThresholdPercent; } /// @notice Get the severe undercollateralization level for this Deposit. /// @dev This collateralization level is critical. If the collateralization /// level falls below this percentage the Deposit can get liquidated. /// This value represents the percentage of the backing BTC value the /// signers must hold as bond in order to not be severely /// undercollateralized. It is set at creation time. Note that the /// value for new deposits in TBTCSystem can be changed by governance, /// but the value for a particular deposit is static once the deposit /// is created. /// @return The severely undercollateralized level for this deposit. function severelyUndercollateralizedThresholdPercent() external view returns (uint16) { return self.severelyUndercollateralizedThresholdPercent; } /// @notice Get the value of the funding UTXO. /// @dev This call will revert if the deposit is not in a state where the /// UTXO info should be valid. In particular, before funding proof is /// successfully submitted (i.e. in states START, /// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), this value /// would not be valid. /// @return The value of the funding UTXO in satoshis. function utxoValue() external view returns (uint256){ require( ! self.inFunding(), "Deposit has not yet been funded and has no available funding info" ); return self.utxoValue(); } /// @notice Returns information associated with the funding UXTO. /// @dev This call will revert if the deposit is not in a state where the /// funding info should be valid. In particular, before funding proof /// is successfully submitted (i.e. in states START, /// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), none of /// these values are set or valid. /// @return A tuple of (uxtoValueBytes, fundedAt, uxtoOutpoint). function fundingInfo() external view returns (bytes8 utxoValueBytes, uint256 fundedAt, bytes memory utxoOutpoint) { require( ! self.inFunding(), "Deposit has not yet been funded and has no available funding info" ); return (self.utxoValueBytes, self.fundedAt, self.utxoOutpoint); } /// @notice Calculates the amount of value at auction right now. /// @dev This call will revert if the deposit is not in a state where an /// auction is currently in progress. /// @return The value in wei that would be received in exchange for the /// deposit's lot size in TBTC if `purchaseSignerBondsAtAuction` /// were called at the time this function is called. function auctionValue() external view returns (uint256) { require( self.inSignerLiquidation(), "Deposit has no funds currently at auction" ); return self.auctionValue(); } /// @notice Get caller's ETH withdraw allowance. /// @dev Generally ETH is only available to withdraw after the deposit /// reaches a closed state. The amount reported is for the sender, and /// can be withdrawn using `withdrawFunds` if the deposit is in an end /// state. /// @return The withdraw allowance in wei. function withdrawableAmount() external view returns (uint256) { return self.getWithdrawableAmount(); } //------------------------------ FUNDING FLOW --------------------------------// /// @notice Notify the contract that signing group setup has timed out if /// retrieveSignerPubkey is not successfully called within the /// allotted time. /// @dev This is considered a signer fault, and the signers' bonds are used /// to make the deposit setup fee available for withdrawal by the TDT /// holder as a refund. The remainder of the signers' bonds are /// returned to the bonding pool and the signers are released from any /// further responsibilities. Reverts if the deposit is not awaiting /// signer setup or if the signing group formation timeout has not /// elapsed. function notifySignerSetupFailed() external { self.notifySignerSetupFailed(); } /// @notice Notify the contract that the ECDSA keep has generated a public /// key so the deposit contract can pull it in. /// @dev Stores the pubkey as 2 bytestrings, X and Y. Emits a /// RegisteredPubkey event with the two components. Reverts if the /// deposit is not awaiting signer setup, if the generated public key /// is unset or has incorrect length, or if the public key has a 0 /// X or Y value. function retrieveSignerPubkey() external { self.retrieveSignerPubkey(); } /// @notice Notify the contract that the funding phase of the deposit has /// timed out if `provideBTCFundingProof` is not successfully called /// within the allotted time. Any sent BTC is left under control of /// the signer group, and the funder can use `requestFunderAbort` to /// request an at-signer-discretion return of any BTC sent to a /// deposit that has been notified of a funding timeout. /// @dev This is considered a funder fault, and the funder's payment for /// opening the deposit is not refunded. Emits a SetupFailed event. /// Reverts if the funding timeout has not yet elapsed, or if the /// deposit is not currently awaiting funding proof. function notifyFundingTimedOut() external { self.notifyFundingTimedOut(); } /// @notice Requests a funder abort for a failed-funding deposit; that is, /// requests the return of a sent UTXO to _abortOutputScript. It /// imposes no requirements on the signing group. Signers should /// send their UTXO to the requested output script, but do so at /// their discretion and with no penalty for failing to do so. This /// can be used for example when a UTXO is sent that is the wrong /// size for the lot. /// @dev This is a self-admitted funder fault, and is only be callable by /// the TDT holder. This function emits the FunderAbortRequested event, /// but stores no additional state. /// @param _abortOutputScript The output script the funder wishes to request /// a return of their UTXO to. function requestFunderAbort(bytes memory _abortOutputScript) public { // not external to allow bytes memory parameters require( self.depositOwner() == msg.sender, "Only TDT holder can request funder abort" ); self.requestFunderAbort(_abortOutputScript); } /// @notice Anyone can provide a signature corresponding to the signers' /// public key to prove fraud during funding. Note that during /// funding no signature has been requested from the signers, so /// any signature is effectively fraud. /// @dev Calls out to the keep to verify if there was fraud. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature (v,r,s) tuple. /// @param _preimage The sha256 preimage of the digest. function provideFundingECDSAFraudProof( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters self.provideFundingECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage); } /// @notice Anyone may submit a funding proof to the deposit showing that /// a transaction was submitted and sufficiently confirmed on the /// Bitcoin chain transferring the deposit lot size's amount of BTC /// to the signer-controlled private key corresopnding to this /// deposit. This will move the deposit into an active state. /// @dev Takes a pre-parsed transaction and calculates values needed to /// verify funding. /// @param _txVersion Transaction version number (4-byte little-endian). /// @param _txInputVector All transaction inputs prepended by the number of /// inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number /// of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector /// (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a /// block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, /// lowest height first. function provideBTCFundingProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters self.provideBTCFundingProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); } //---------------------------- LIQUIDATION FLOW ------------------------------// /// @notice Notify the contract that the signers are undercollateralized. /// @dev This call will revert if the signers are not in fact /// undercollateralized according to the price feed. After /// TBTCConstants.COURTESY_CALL_DURATION, courtesy call times out and /// regular abort liquidation occurs; see /// `notifyCourtesyTimedOut`. function notifyCourtesyCall() external { self.notifyCourtesyCall(); } /// @notice Notify the contract that the signers' bond value has recovered /// enough to be considered sufficiently collateralized. /// @dev This call will revert if collateral is still below the /// undercollateralized threshold according to the price feed. function exitCourtesyCall() external { self.exitCourtesyCall(); } /// @notice Notify the contract that the courtesy period has expired and the /// deposit should move into liquidation. /// @dev This call will revert if the courtesy call period has not in fact /// expired or is not in the courtesy call state. Courtesy call /// expiration is treated as an abort, and is handled by seizing signer /// bonds and putting them up for auction for the lot size amount in /// TBTC (see `purchaseSignerBondsAtAuction`). Emits a /// LiquidationStarted event. The caller is captured as the liquidation /// initiator, and is eligible for 50% of any bond left after the /// auction is completed. function notifyCourtesyCallExpired() external { self.notifyCourtesyCallExpired(); } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @dev This call will revert if the signers are not in fact severely /// undercollateralized according to the price feed. Severe /// undercollateralization is treated as an abort, and is handled by /// seizing signer bonds and putting them up for auction in exchange /// for the lot size amount in TBTC (see /// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event. /// The caller is captured as the liquidation initiator, and is /// eligible for 50% of any bond left after the auction is completed. function notifyUndercollateralizedLiquidation() external { self.notifyUndercollateralizedLiquidation(); } /// @notice Anyone can provide a signature corresponding to the signers' /// public key that was not requested to prove fraud. A redemption /// request and a redemption fee increase are the only ways to /// request a signature from the signers. /// @dev This call will revert if the underlying keep cannot verify that /// there was fraud. Fraud is handled by seizing signer bonds and /// putting them up for auction in exchange for the lot size amount in /// TBTC (see `purchaseSignerBondsAtAuction`). Emits a /// LiquidationStarted event. The caller is captured as the liquidation /// initiator, and is eligible for any bond left after the auction is /// completed. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature (v,r,s) tuple. /// @param _preimage The sha256 preimage of the digest. function provideECDSAFraudProof( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters self.provideECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage); } /// @notice Notify the contract that the signers have failed to produce a /// signature for a redemption request in the allotted time. /// @dev This is considered an abort, and is punished by seizing signer /// bonds and putting them up for auction. Emits a LiquidationStarted /// event and a Liquidated event and sends the full signer bond to the /// redeemer. Reverts if the deposit is not currently awaiting a /// signature or if the allotted time has not yet elapsed. The caller /// is captured as the liquidation initiator, and is eligible for 50% /// of any bond left after the auction is completed. function notifyRedemptionSignatureTimedOut() external { self.notifyRedemptionSignatureTimedOut(); } /// @notice Notify the contract that the deposit has failed to receive a /// redemption proof in the allotted time. /// @dev This call will revert if the deposit is not currently awaiting a /// signature or if the allotted time has not yet elapsed. This is /// considered an abort, and is punished by seizing signer bonds and /// putting them up for auction for the lot size amount in TBTC (see /// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event. /// The caller is captured as the liquidation initiator, and /// is eligible for 50% of any bond left after the auction is /// completed. function notifyRedemptionProofTimedOut() external { self.notifyRedemptionProofTimedOut(); } /// @notice Closes an auction and purchases the signer bonds by transferring /// the lot size in TBTC to the redeemer, if there is one, or to the /// TDT holder if not. Any bond amount that is not currently up for /// auction is either made available for the liquidation initiator /// to withdraw (for fraud) or split 50-50 between the initiator and /// the signers (for abort or collateralization issues). /// @dev The amount of ETH given for the transferred TBTC can be read using /// the `auctionValue` function; note, however, that the function's /// value is only static during the specific block it is queried, as it /// varies by block timestamp. function purchaseSignerBondsAtAuction() external { self.purchaseSignerBondsAtAuction(); } //---------------------------- REDEMPTION FLOW -------------------------------// /// @notice Get TBTC amount required for redemption by a specified /// _redeemer. /// @dev This call will revert if redemption is not possible by _redeemer. /// @param _redeemer The deposit redeemer whose TBTC requirement is being /// requested. /// @return The amount in TBTC needed by the `_redeemer` to redeem the /// deposit. function getRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){ (uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, false); return tbtcPayment; } /// @notice Get TBTC amount required for redemption assuming _redeemer /// is this deposit's owner (TDT holder). /// @param _redeemer The assumed owner of the deposit's TDT . /// @return The amount in TBTC needed to redeem the deposit. function getOwnerRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){ (uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, true); return tbtcPayment; } /// @notice Requests redemption of this deposit, meaning the transmission, /// by the signers, of the deposit's UTXO to the specified Bitocin /// output script. Requires approving the deposit to spend the /// amount of TBTC needed to redeem. /// @dev The amount of TBTC needed to redeem can be looked up using the /// `getRedemptionTbtcRequirement` or `getOwnerRedemptionTbtcRequirement` /// functions. /// @param _outputValueBytes The 8-byte little-endian output size. The /// difference between this value and the lot size of the deposit /// will be paid as a fee to the Bitcoin miners when the signed /// transaction is broadcast. /// @param _redeemerOutputScript The redeemer's length-prefixed output /// script. function requestRedemption( bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters self.requestRedemption(_outputValueBytes, _redeemerOutputScript); } /// @notice Anyone may provide a withdrawal signature if it was requested. /// @dev The signers will be penalized if this function is not called /// correctly within `TBTCConstants.REDEMPTION_SIGNATURE_TIMEOUT` /// seconds of a redemption request or fee increase being received. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. Should be in the low half of secp256k1 /// curve's order. function provideRedemptionSignature( uint8 _v, bytes32 _r, bytes32 _s ) external { self.provideRedemptionSignature(_v, _r, _s); } /// @notice Anyone may request a signature for a transaction with an /// increased Bitcoin transaction fee. /// @dev This call will revert if the fee is already at its maximum, or if /// the new requested fee is not a multiple of the initial requested /// fee. Transaction fees can only be bumped by the amount of the /// initial requested fee. Calling this sends the deposit back to /// the `AWAITING_WITHDRAWAL_SIGNATURE` state and requires the signers /// to `provideRedemptionSignature` for the new output value in a /// timely fashion. /// @param _previousOutputValueBytes The previous output's value. /// @param _newOutputValueBytes The new output's value. function increaseRedemptionFee( bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) external { self.increaseRedemptionFee(_previousOutputValueBytes, _newOutputValueBytes); } /// @notice Anyone may submit a redemption proof to the deposit showing that /// a transaction was submitted and sufficiently confirmed on the /// Bitcoin chain transferring the deposit lot size's amount of BTC /// from the signer-controlled private key corresponding to this /// deposit to the requested redemption output script. This will /// move the deposit into a redeemed state. /// @dev Takes a pre-parsed transaction and calculates values needed to /// verify funding. Signers can have their bonds seized if this is not /// called within `TBTCConstants.REDEMPTION_PROOF_TIMEOUT` seconds of /// a redemption signature being provided. /// @param _txVersion Transaction version number (4-byte little-endian). /// @param _txInputVector All transaction inputs prepended by the number of /// inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number /// of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _merkleProof The merkle proof of transaction inclusion in a /// block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, /// lowest height first. function provideRedemptionProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters self.provideRedemptionProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); } //--------------------------- MUTATING HELPERS -------------------------------// /// @notice This function can only be called by the deposit factory; use /// `DepositFactory.createDeposit` to create a new deposit. /// @dev Initializes a new deposit clone with the base state for the /// deposit. /// @param _tbtcSystem `TBTCSystem` contract. More info in `TBTCSystem`. /// @param _tbtcToken `TBTCToken` contract. More info in TBTCToken`. /// @param _tbtcDepositToken `TBTCDepositToken` (TDT) contract. More info in /// `TBTCDepositToken`. /// @param _feeRebateToken `FeeRebateToken` (FRT) contract. More info in /// `FeeRebateToken`. /// @param _vendingMachineAddress `VendingMachine` address. More info in /// `VendingMachine`. /// @param _lotSizeSatoshis The minimum amount of satoshi the funder is /// required to send. This is also the amount of /// TBTC the TDT holder will be eligible to mint: /// (10**7 satoshi == 0.1 BTC == 0.1 TBTC). function initializeDeposit( ITBTCSystem _tbtcSystem, TBTCToken _tbtcToken, IERC721 _tbtcDepositToken, FeeRebateToken _feeRebateToken, address _vendingMachineAddress, uint64 _lotSizeSatoshis ) public onlyFactory payable { self.tbtcSystem = _tbtcSystem; self.tbtcToken = _tbtcToken; self.tbtcDepositToken = _tbtcDepositToken; self.feeRebateToken = _feeRebateToken; self.vendingMachineAddress = _vendingMachineAddress; self.initialize(_lotSizeSatoshis); } /// @notice This function can only be called by the vending machine. /// @dev Performs the same action as requestRedemption, but transfers /// ownership of the deposit to the specified _finalRecipient. Used as /// a utility helper for the vending machine's shortcut /// TBTC->redemption path. /// @param _outputValueBytes The 8-byte little-endian output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer. function transferAndRequestRedemption( bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _finalRecipient ) public { // not external to allow bytes memory parameters require( msg.sender == self.vendingMachineAddress, "Only the vending machine can call transferAndRequestRedemption" ); self.transferAndRequestRedemption( _outputValueBytes, _redeemerOutputScript, _finalRecipient ); } /// @notice Withdraw the ETH balance of the deposit allotted to the caller. /// @dev Withdrawals can only happen when a contract is in an end-state. function withdrawFunds() external { self.withdrawFunds(); } } pragma solidity 0.5.17; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {DepositStates} from "./DepositStates.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; library DepositLiquidation { using BTCUtils for bytes; using BytesLib for bytes; using SafeMath for uint256; using SafeMath for uint64; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Notifies the keep contract of fraud. Reverts if not fraud. /// @dev Calls out to the keep contract. this could get expensive if preimage /// is large. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. function submitSignatureFraud( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.submitSignatureFraud(_v, _r, _s, _signedDigest, _preimage); } /// @notice Determines the collateralization percentage of the signing group. /// @dev Compares the bond value and lot value. /// @param _d Deposit storage pointer. /// @return Collateralization percentage as uint. function collateralizationPercentage(DepositUtils.Deposit storage _d) public view returns (uint256) { // Determine value of the lot in wei uint256 _satoshiPrice = _d.fetchBitcoinPrice(); uint64 _lotSizeSatoshis = _d.lotSizeSatoshis; uint256 _lotValue = _lotSizeSatoshis.mul(_satoshiPrice); // Amount of wei the signers have uint256 _bondValue = _d.fetchBondAmount(); // This converts into a percentage return (_bondValue.mul(100).div(_lotValue)); } /// @dev Starts signer liquidation by seizing signer bonds. /// If the deposit is currently being redeemed, the redeemer /// receives the full bond value; otherwise, a falling price auction /// begins to buy 1 TBTC in exchange for a portion of the seized bonds; /// see purchaseSignerBondsAtAuction(). /// @param _wasFraud True if liquidation is being started due to fraud, false if for any other reason. /// @param _d Deposit storage pointer. function startLiquidation(DepositUtils.Deposit storage _d, bool _wasFraud) internal { _d.logStartedLiquidation(_wasFraud); uint256 seized = _d.seizeSignerBonds(); address redeemerAddress = _d.redeemerAddress; // Reclaim used state for gas savings _d.redemptionTeardown(); // If we see fraud in the redemption flow, we shouldn't go to auction. // Instead give the full signer bond directly to the redeemer. if (_d.inRedemption() && _wasFraud) { _d.setLiquidated(); _d.enableWithdrawal(redeemerAddress, seized); _d.logLiquidated(); return; } _d.liquidationInitiator = msg.sender; _d.liquidationInitiated = block.timestamp; // Store the timestamp for auction if(_wasFraud){ _d.setFraudLiquidationInProgress(); } else{ _d.setLiquidationInProgress(); } } /// @notice Anyone can provide a signature that was not requested to prove fraud. /// @dev Calls out to the keep to verify if there was fraud. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. function provideECDSAFraudProof( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters require( !_d.inFunding(), "Use provideFundingECDSAFraudProof instead" ); require( !_d.inSignerLiquidation(), "Signer liquidation already in progress" ); require(!_d.inEndState(), "Contract has halted"); submitSignatureFraud(_d, _v, _r, _s, _signedDigest, _preimage); startLiquidation(_d, true); } /// @notice Closes an auction and purchases the signer bonds. Payout to buyer, funder, then signers if not fraud. /// @dev For interface, reading auctionValue will give a past value. the current is better. /// @param _d Deposit storage pointer. function purchaseSignerBondsAtAuction(DepositUtils.Deposit storage _d) external { bool _wasFraud = _d.inFraudLiquidationInProgress(); require(_d.inSignerLiquidation(), "No active auction"); _d.setLiquidated(); _d.logLiquidated(); // Send the TBTC to the redeemer if they exist, otherwise to the TDT // holder. If the TDT holder is the Vending Machine, burn it to maintain // the peg. This is because, if there is a redeemer set here, the TDT // holder has already been made whole at redemption request time. address tbtcRecipient = _d.redeemerAddress; if (tbtcRecipient == address(0)) { tbtcRecipient = _d.depositOwner(); } uint256 lotSizeTbtc = _d.lotSizeTbtc(); require(_d.tbtcToken.balanceOf(msg.sender) >= lotSizeTbtc, "Not enough TBTC to cover outstanding debt"); if(tbtcRecipient == _d.vendingMachineAddress){ _d.tbtcToken.burnFrom(msg.sender, lotSizeTbtc); // burn minimal amount to cover size } else{ _d.tbtcToken.transferFrom(msg.sender, tbtcRecipient, lotSizeTbtc); } // Distribute funds to auction buyer uint256 valueToDistribute = _d.auctionValue(); _d.enableWithdrawal(msg.sender, valueToDistribute); // Send any TBTC left to the Fee Rebate Token holder _d.distributeFeeRebate(); // For fraud, pay remainder to the liquidation initiator. // For non-fraud, split 50-50 between initiator and signers. if the transfer amount is 1, // division will yield a 0 value which causes a revert; instead, // we simply ignore such a tiny amount and leave some wei dust in escrow uint256 contractEthBalance = address(this).balance; address payable initiator = _d.liquidationInitiator; if (initiator == address(0)){ initiator = address(0xdead); } if (contractEthBalance > valueToDistribute + 1) { uint256 remainingUnallocated = contractEthBalance.sub(valueToDistribute); if (_wasFraud) { _d.enableWithdrawal(initiator, remainingUnallocated); } else { // There will always be a liquidation initiator. uint256 split = remainingUnallocated.div(2); _d.pushFundsToKeepGroup(split); _d.enableWithdrawal(initiator, remainingUnallocated.sub(split)); } } } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @param _d Deposit storage pointer. function notifyCourtesyCall(DepositUtils.Deposit storage _d) external { require(_d.inActive(), "Can only courtesy call from active state"); require(collateralizationPercentage(_d) < _d.undercollateralizedThresholdPercent, "Signers have sufficient collateral"); _d.courtesyCallInitiated = block.timestamp; _d.setCourtesyCall(); _d.logCourtesyCalled(); } /// @notice Goes from courtesy call to active. /// @dev Only callable if collateral is sufficient and the deposit is not expiring. /// @param _d Deposit storage pointer. function exitCourtesyCall(DepositUtils.Deposit storage _d) external { require(_d.inCourtesyCall(), "Not currently in courtesy call"); require(collateralizationPercentage(_d) >= _d.undercollateralizedThresholdPercent, "Deposit is still undercollateralized"); _d.setActive(); _d.logExitedCourtesyCall(); } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @param _d Deposit storage pointer. function notifyUndercollateralizedLiquidation(DepositUtils.Deposit storage _d) external { require(_d.inRedeemableState(), "Deposit not in active or courtesy call"); require(collateralizationPercentage(_d) < _d.severelyUndercollateralizedThresholdPercent, "Deposit has sufficient collateral"); startLiquidation(_d, false); } /// @notice Notifies the contract that the courtesy period has elapsed. /// @dev This is treated as an abort, rather than fraud. /// @param _d Deposit storage pointer. function notifyCourtesyCallExpired(DepositUtils.Deposit storage _d) external { require(_d.inCourtesyCall(), "Not in a courtesy call period"); require(block.timestamp >= _d.courtesyCallInitiated.add(TBTCConstants.getCourtesyCallTimeout()), "Courtesy period has not elapsed"); startLiquidation(_d, false); } } pragma solidity ^0.5.10; /** @title BitcoinSPV */ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {SafeMath} from "./SafeMath.sol"; library BTCUtils { using BytesLib for bytes; using SafeMath for uint256; // The target at minimum Difficulty. Also the target of the genesis block uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000; uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; /* ***** */ /* UTILS */ /* ***** */ /// @notice Determines the length of a VarInt in bytes /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length /// @param _flag The first byte of a VarInt /// @return The number of non-flag bytes in the VarInt function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) { if (uint8(_flag[0]) == 0xff) { return 8; // one-byte flag, 8 bytes data } if (uint8(_flag[0]) == 0xfe) { return 4; // one-byte flag, 4 bytes data } if (uint8(_flag[0]) == 0xfd) { return 2; // one-byte flag, 2 bytes data } return 0; // flag is data } /// @notice Parse a VarInt into its data length and the number it represents /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes. /// Caller SHOULD explicitly handle this case (or bubble it up) /// @param _b A byte-string starting with a VarInt /// @return number of bytes in the encoding (not counting the tag), the encoded int function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) { uint8 _dataLen = determineVarIntDataLength(_b); if (_dataLen == 0) { return (0, uint8(_b[0])); } if (_b.length < 1 + _dataLen) { return (ERR_BAD_ARG, 0); } uint256 _number = bytesToUint(reverseEndianness(_b.slice(1, _dataLen))); return (_dataLen, _number); } /// @notice Changes the endianness of a byte array /// @dev Returns a new, backwards, bytes /// @param _b The bytes to reverse /// @return The reversed bytes function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) { bytes memory _newValue = new bytes(_b.length); for (uint i = 0; i < _b.length; i++) { _newValue[_b.length - i - 1] = _b[i]; } return _newValue; } /// @notice Changes the endianness of a uint256 /// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel /// @param _b The unsigned integer to reverse /// @return The reversed value function reverseUint256(uint256 _b) internal pure returns (uint256 v) { v = _b; // swap bytes v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } /// @notice Converts big-endian bytes to a uint /// @dev Traverses the byte array and sums the bytes /// @param _b The big-endian bytes-encoded integer /// @return The integer representation function bytesToUint(bytes memory _b) internal pure returns (uint256) { uint256 _number; for (uint i = 0; i < _b.length; i++) { _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1)))); } return _number; } /// @notice Get the last _num bytes from a byte array /// @param _b The byte array to slice /// @param _num The number of bytes to extract from the end /// @return The last _num bytes of _b function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { uint256 _start = _b.length.sub(_num); return _b.slice(_start, _num); } /// @notice Implements bitcoin's hash160 (rmd160(sha2())) /// @dev abi.encodePacked changes the return to bytes instead of bytes32 /// @param _b The pre-image /// @return The digest function hash160(bytes memory _b) internal pure returns (bytes memory) { return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b)))); } /// @notice Implements bitcoin's hash256 (double sha2) /// @dev abi.encodePacked changes the return to bytes instead of bytes32 /// @param _b The pre-image /// @return The digest function hash256(bytes memory _b) internal pure returns (bytes32) { return sha256(abi.encodePacked(sha256(_b))); } /// @notice Implements bitcoin's hash256 (double sha2) /// @dev sha2 is precompiled smart contract located at address(2) /// @param _b The pre-image /// @return The digest function hash256View(bytes memory _b) internal view returns (bytes32 res) { // solium-disable-next-line security/no-inline-assembly assembly { let ptr := mload(0x40) pop(staticcall(gas, 2, add(_b, 32), mload(_b), ptr, 32)) pop(staticcall(gas, 2, ptr, 32, ptr, 32)) res := mload(ptr) } } /* ************ */ /* Legacy Input */ /* ************ */ /// @notice Extracts the nth input from the vin (0-indexed) /// @dev Iterates over the vin. If you need to extract several, write a custom function /// @param _vin The vin as a tightly-packed byte array /// @param _index The 0-indexed location of the input to extract /// @return The input as a byte array function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _nIns; (_varIntDataLen, _nIns) = parseVarInt(_vin); require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing"); require(_index < _nIns, "Vin read overrun"); bytes memory _remaining; uint256 _len = 0; uint256 _offset = 1 + _varIntDataLen; for (uint256 _i = 0; _i < _index; _i ++) { _remaining = _vin.slice(_offset, _vin.length - _offset); _len = determineInputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig"); _offset = _offset + _len; } _remaining = _vin.slice(_offset, _vin.length - _offset); _len = determineInputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig"); return _vin.slice(_offset, _len); } /// @notice Determines whether an input is legacy /// @dev False if no scriptSig, otherwise True /// @param _input The input /// @return True for legacy, False for witness function isLegacyInput(bytes memory _input) internal pure returns (bool) { return _input.keccak256Slice(36, 1) != keccak256(hex"00"); } /// @notice Determines the length of a scriptSig in an input /// @dev Will return 0 if passed a witness input. /// @param _input The LEGACY input /// @return The length of the script sig function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) { if (_input.length < 37) { return (ERR_BAD_ARG, 0); } bytes memory _afterOutpoint = _input.slice(36, _input.length - 36); uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = parseVarInt(_afterOutpoint); return (_varIntDataLen, _scriptSigLen); } /// @notice Determines the length of an input from its scriptSig /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence /// @param _input The input /// @return The length of the input in bytes function determineInputLength(bytes memory _input) internal pure returns (uint256) { uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); if (_varIntDataLen == ERR_BAD_ARG) { return ERR_BAD_ARG; } return 36 + 1 + _varIntDataLen + _scriptSigLen + 4; } /// @notice Extracts the LE sequence bytes from an input /// @dev Sequence is used for relative time locks /// @param _input The LEGACY input /// @return The sequence bytes (LE uint) function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig"); return _input.slice(36 + 1 + _varIntDataLen + _scriptSigLen, 4); } /// @notice Extracts the sequence from the input /// @dev Sequence is a 4-byte little-endian number /// @param _input The LEGACY input /// @return The sequence number (big-endian uint) function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) { bytes memory _leSeqence = extractSequenceLELegacy(_input); bytes memory _beSequence = reverseEndianness(_leSeqence); return uint32(bytesToUint(_beSequence)); } /// @notice Extracts the VarInt-prepended scriptSig from the input in a tx /// @dev Will return hex"00" if passed a witness input /// @param _input The LEGACY input /// @return The length-prepended scriptSig function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig"); return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen); } /* ************* */ /* Witness Input */ /* ************* */ /// @notice Extracts the LE sequence bytes from an input /// @dev Sequence is used for relative time locks /// @param _input The WITNESS input /// @return The sequence bytes (LE uint) function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(37, 4); } /// @notice Extracts the sequence from the input in a tx /// @dev Sequence is a 4-byte little-endian number /// @param _input The WITNESS input /// @return The sequence number (big-endian uint) function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) { bytes memory _leSeqence = extractSequenceLEWitness(_input); bytes memory _inputeSequence = reverseEndianness(_leSeqence); return uint32(bytesToUint(_inputeSequence)); } /// @notice Extracts the outpoint from the input in a tx /// @dev 32-byte tx id with 4-byte index /// @param _input The input /// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index) function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(0, 36); } /// @notice Extracts the outpoint tx id from an input /// @dev 32-byte tx id /// @param _input The input /// @return The tx id (little-endian bytes) function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) { return _input.slice(0, 32).toBytes32(); } /// @notice Extracts the LE tx input index from the input in a tx /// @dev 4-byte tx index /// @param _input The input /// @return The tx index (little-endian bytes) function extractTxIndexLE(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(32, 4); } /* ****** */ /* Output */ /* ****** */ /// @notice Determines the length of an output /// @dev Works with any properly formatted output /// @param _output The output /// @return The length indicated by the prefix, error if invalid length function determineOutputLength(bytes memory _output) internal pure returns (uint256) { if (_output.length < 9) { return ERR_BAD_ARG; } bytes memory _afterValue = _output.slice(8, _output.length - 8); uint256 _varIntDataLen; uint256 _scriptPubkeyLength; (_varIntDataLen, _scriptPubkeyLength) = parseVarInt(_afterValue); if (_varIntDataLen == ERR_BAD_ARG) { return ERR_BAD_ARG; } // 8-byte value, 1-byte for tag itself return 8 + 1 + _varIntDataLen + _scriptPubkeyLength; } /// @notice Extracts the output at a given index in the TxOuts vector /// @dev Iterates over the vout. If you need to extract multiple, write a custom function /// @param _vout The _vout to extract from /// @param _index The 0-indexed location of the output to extract /// @return The specified output function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _nOuts; (_varIntDataLen, _nOuts) = parseVarInt(_vout); require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing"); require(_index < _nOuts, "Vout read overrun"); bytes memory _remaining; uint256 _len = 0; uint256 _offset = 1 + _varIntDataLen; for (uint256 _i = 0; _i < _index; _i ++) { _remaining = _vout.slice(_offset, _vout.length - _offset); _len = determineOutputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey"); _offset += _len; } _remaining = _vout.slice(_offset, _vout.length - _offset); _len = determineOutputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey"); return _vout.slice(_offset, _len); } /// @notice Extracts the value bytes from the output in a tx /// @dev Value is an 8-byte little-endian number /// @param _output The output /// @return The output value as LE bytes function extractValueLE(bytes memory _output) internal pure returns (bytes memory) { return _output.slice(0, 8); } /// @notice Extracts the value from the output in a tx /// @dev Value is an 8-byte little-endian number /// @param _output The output /// @return The output value function extractValue(bytes memory _output) internal pure returns (uint64) { bytes memory _leValue = extractValueLE(_output); bytes memory _beValue = reverseEndianness(_leValue); return uint64(bytesToUint(_beValue)); } /// @notice Extracts the data from an op return output /// @dev Returns hex"" if no data or not an op return /// @param _output The output /// @return Any data contained in the opreturn output, null if not an op return function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) { if (_output.keccak256Slice(9, 1) != keccak256(hex"6a")) { return hex""; } bytes memory _dataLen = _output.slice(10, 1); return _output.slice(11, bytesToUint(_dataLen)); } /// @notice Extracts the hash from the output script /// @dev Determines type by the length prefix and validates format /// @param _output The output /// @return The hash committed to by the pk_script, or null for errors function extractHash(bytes memory _output) internal pure returns (bytes memory) { uint8 _scriptLen = uint8(_output[8]); // don't have to worry about overflow here. // if _scriptLen + 9 overflows, then output.length would have to be < 9 // for this check to pass. if it's < 9, then we errored when assigning // _scriptLen if (_scriptLen + 9 != _output.length) { return hex""; } if (uint8(_output[9]) == 0) { if (_scriptLen < 2) { return hex""; } uint256 _payloadLen = uint8(_output[10]); // Check for maliciously formatted witness outputs. // No need to worry about underflow as long b/c of the `< 2` check if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) { return hex""; } return _output.slice(11, _payloadLen); } else { bytes32 _tag = _output.keccak256Slice(8, 3); // p2pkh if (_tag == keccak256(hex"1976a9")) { // Check for maliciously formatted p2pkh // No need to worry about underflow, b/c of _scriptLen check if (uint8(_output[11]) != 0x14 || _output.keccak256Slice(_output.length - 2, 2) != keccak256(hex"88ac")) { return hex""; } return _output.slice(12, 20); //p2sh } else if (_tag == keccak256(hex"17a914")) { // Check for maliciously formatted p2sh // No need to worry about underflow, b/c of _scriptLen check if (uint8(_output[_output.length - 1]) != 0x87) { return hex""; } return _output.slice(11, 20); } } return hex""; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */ } /* ********** */ /* Witness TX */ /* ********** */ /// @notice Checks that the vin passed up is properly formatted /// @dev Consider a vin with a valid vout in its scriptsig /// @param _vin Raw bytes length-prefixed input vector /// @return True if it represents a validly formatted vin function validateVin(bytes memory _vin) internal pure returns (bool) { uint256 _varIntDataLen; uint256 _nIns; (_varIntDataLen, _nIns) = parseVarInt(_vin); // Not valid if it says there are too many or no inputs if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) { return false; } uint256 _offset = 1 + _varIntDataLen; for (uint256 i = 0; i < _nIns; i++) { // If we're at the end, but still expect more if (_offset >= _vin.length) { return false; } // Grab the next input and determine its length. bytes memory _next = _vin.slice(_offset, _vin.length - _offset); uint256 _nextLen = determineInputLength(_next); if (_nextLen == ERR_BAD_ARG) { return false; } // Increase the offset by that much _offset += _nextLen; } // Returns false if we're not exactly at the end return _offset == _vin.length; } /// @notice Checks that the vout passed up is properly formatted /// @dev Consider a vout with a valid scriptpubkey /// @param _vout Raw bytes length-prefixed output vector /// @return True if it represents a validly formatted vout function validateVout(bytes memory _vout) internal pure returns (bool) { uint256 _varIntDataLen; uint256 _nOuts; (_varIntDataLen, _nOuts) = parseVarInt(_vout); // Not valid if it says there are too many or no outputs if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) { return false; } uint256 _offset = 1 + _varIntDataLen; for (uint256 i = 0; i < _nOuts; i++) { // If we're at the end, but still expect more if (_offset >= _vout.length) { return false; } // Grab the next output and determine its length. // Increase the offset by that much bytes memory _next = _vout.slice(_offset, _vout.length - _offset); uint256 _nextLen = determineOutputLength(_next); if (_nextLen == ERR_BAD_ARG) { return false; } _offset += _nextLen; } // Returns false if we're not exactly at the end return _offset == _vout.length; } /* ************ */ /* Block Header */ /* ************ */ /// @notice Extracts the transaction merkle root from a block header /// @dev Use verifyHash256Merkle to verify proofs with this root /// @param _header The header /// @return The merkle root (little-endian) function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(36, 32); } /// @notice Extracts the target from a block header /// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent /// @param _header The header /// @return The target threshold function extractTarget(bytes memory _header) internal pure returns (uint256) { bytes memory _m = _header.slice(72, 3); uint8 _e = uint8(_header[75]); uint256 _mantissa = bytesToUint(reverseEndianness(_m)); uint _exponent = _e - 3; return _mantissa * (256 ** _exponent); } /// @notice Calculate difficulty from the difficulty 1 target and current target /// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet /// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent /// @param _target The current target /// @return The block difficulty (bdiff) function calculateDifficulty(uint256 _target) internal pure returns (uint256) { // Difficulty 1 calculated from 0x1d00ffff return DIFF1_TARGET.div(_target); } /// @notice Extracts the previous block's hash from a block header /// @dev Block headers do NOT include block number :( /// @param _header The header /// @return The previous block's hash (little-endian) function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(4, 32); } /// @notice Extracts the timestamp from a block header /// @dev Time is not 100% reliable /// @param _header The header /// @return The timestamp (little-endian bytes) function extractTimestampLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(68, 4); } /// @notice Extracts the timestamp from a block header /// @dev Time is not 100% reliable /// @param _header The header /// @return The timestamp (uint) function extractTimestamp(bytes memory _header) internal pure returns (uint32) { return uint32(bytesToUint(reverseEndianness(extractTimestampLE(_header)))); } /// @notice Extracts the expected difficulty from a block header /// @dev Does NOT verify the work /// @param _header The header /// @return The difficulty as an integer function extractDifficulty(bytes memory _header) internal pure returns (uint256) { return calculateDifficulty(extractTarget(_header)); } /// @notice Concatenates and hashes two inputs for merkle proving /// @param _a The first hash /// @param _b The second hash /// @return The double-sha256 of the concatenated hashes function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { return hash256(abi.encodePacked(_a, _b)); } /// @notice Verifies a Bitcoin-style merkle tree /// @dev Leaves are 0-indexed. /// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root /// @param _index The index of the leaf /// @return true if the proof is valid, else false function verifyHash256Merkle(bytes memory _proof, uint _index) internal pure returns (bool) { // Not an even number of hashes if (_proof.length % 32 != 0) { return false; } // Special case for coinbase-only blocks if (_proof.length == 32) { return true; } // Should never occur if (_proof.length == 64) { return false; } uint _idx = _index; bytes32 _root = _proof.slice(_proof.length - 32, 32).toBytes32(); bytes32 _current = _proof.slice(0, 32).toBytes32(); for (uint i = 1; i < (_proof.length.div(32)) - 1; i++) { if (_idx % 2 == 1) { _current = _hash256MerkleStep(_proof.slice(i * 32, 32), abi.encodePacked(_current)); } else { _current = _hash256MerkleStep(abi.encodePacked(_current), _proof.slice(i * 32, 32)); } _idx = _idx >> 1; } return _current == _root; } /* NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72 NB: We get a full-bitlength target from this. For comparison with header-encoded targets we need to mask it with the header target e.g. (full & truncated) == truncated */ /// @notice performs the bitcoin difficulty retarget /// @dev implements the Bitcoin algorithm precisely /// @param _previousTarget the target of the previous period /// @param _firstTimestamp the timestamp of the first block in the difficulty period /// @param _secondTimestamp the timestamp of the last block in the difficulty period /// @return the new period's target threshold function retargetAlgorithm( uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp ) internal pure returns (uint256) { uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp); // Normalize ratio to factor of 4 if very long or very short if (_elapsedTime < RETARGET_PERIOD.div(4)) { _elapsedTime = RETARGET_PERIOD.div(4); } if (_elapsedTime > RETARGET_PERIOD.mul(4)) { _elapsedTime = RETARGET_PERIOD.mul(4); } /* NB: high targets e.g. ffff0020 can cause overflows here so we divide it by 256**2, then multiply by 256**2 later we know the target is evenly divisible by 256**2, so this isn't an issue */ uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime); return _adjusted.div(RETARGET_PERIOD).mul(65536); } } pragma solidity ^0.5.10; /* https://github.com/GNSPS/solidity-bytes-utils/ This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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. For more information, please refer to <https://unlicense.org> */ /** @title BytesLib **/ /** @author https://github.com/GNSPS **/ library BytesLib { function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) { if (_length == 0) { return hex""; } uint _end = _start + _length; require(_end > _start && _bytes.length >= _end, "Slice out of bounds"); assembly { // Alloc bytes array with additional 32 bytes afterspace and assign it's size res := mload(0x40) mstore(0x40, add(add(res, 64), _length)) mstore(res, _length) // Compute distance between source and destination pointers let diff := sub(res, add(_bytes, _start)) for { let src := add(add(_bytes, 32), _start) let end := add(src, _length) } lt(src, end) { src := add(src, 32) } { mstore(add(src, diff), mload(src)) } } } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { uint _totalLen = _start + 20; require(_totalLen > _start && _bytes.length >= _totalLen, "Address conversion out of bounds."); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { uint _totalLen = _start + 32; require(_totalLen > _start && _bytes.length >= _totalLen, "Uint conversion out of bounds."); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } function toBytes32(bytes memory _source) pure internal returns (bytes32 result) { if (_source.length == 0) { return 0x0; } assembly { result := mload(add(_source, 32)) } } function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) { uint _end = _start + _length; require(_end > _start && _bytes.length >= _end, "Slice out of bounds"); assembly { result := keccak256(add(add(_bytes, 32), _start), _length) } } } pragma solidity ^0.5.10; /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; require(c / _a == _b, "Overflow during multiplication."); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, "Underflow during subtraction."); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; require(c >= _a, "Overflow during addition."); return c; } } pragma solidity 0.5.17; import {DepositUtils} from "./DepositUtils.sol"; library DepositStates { enum States { // DOES NOT EXIST YET START, // FUNDING FLOW AWAITING_SIGNER_SETUP, AWAITING_BTC_FUNDING_PROOF, // FAILED SETUP FAILED_SETUP, // ACTIVE ACTIVE, // includes courtesy call // REDEMPTION FLOW AWAITING_WITHDRAWAL_SIGNATURE, AWAITING_WITHDRAWAL_PROOF, REDEEMED, // SIGNER LIQUIDATION FLOW COURTESY_CALL, FRAUD_LIQUIDATION_IN_PROGRESS, LIQUIDATION_IN_PROGRESS, LIQUIDATED } /// @notice Check if the contract is currently in the funding flow. /// @dev This checks on the funding flow happy path, not the fraud path. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the funding flow else False. function inFunding(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.AWAITING_SIGNER_SETUP) || _d.currentState == uint8(States.AWAITING_BTC_FUNDING_PROOF) ); } /// @notice Check if the contract is currently in the signer liquidation flow. /// @dev This could be caused by fraud, or by an unfilled margin call. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the liquidaton flow else False. function inSignerLiquidation(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.LIQUIDATION_IN_PROGRESS) || _d.currentState == uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS) ); } /// @notice Check if the contract is currently in the redepmtion flow. /// @dev This checks on the redemption flow, not the REDEEMED termination state. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the redemption flow else False. function inRedemption(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.AWAITING_WITHDRAWAL_SIGNATURE) || _d.currentState == uint8(States.AWAITING_WITHDRAWAL_PROOF) ); } /// @notice Check if the contract has halted. /// @dev This checks on any halt state, regardless of triggering circumstances. /// @param _d Deposit storage pointer. /// @return True if contract has halted permanently. function inEndState(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.LIQUIDATED) || _d.currentState == uint8(States.REDEEMED) || _d.currentState == uint8(States.FAILED_SETUP) ); } /// @notice Check if the contract is available for a redemption request. /// @dev Redemption is available from active and courtesy call. /// @param _d Deposit storage pointer. /// @return True if available, False otherwise. function inRedeemableState(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.ACTIVE) || _d.currentState == uint8(States.COURTESY_CALL) ); } /// @notice Check if the contract is currently in the start state (awaiting setup). /// @dev This checks on the funding flow happy path, not the fraud path. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the start state else False. function inStart(DepositUtils.Deposit storage _d) public view returns (bool) { return (_d.currentState == uint8(States.START)); } function inAwaitingSignerSetup(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_SIGNER_SETUP); } function inAwaitingBTCFundingProof(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_BTC_FUNDING_PROOF); } function inFailedSetup(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.FAILED_SETUP); } function inActive(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.ACTIVE); } function inAwaitingWithdrawalSignature(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_WITHDRAWAL_SIGNATURE); } function inAwaitingWithdrawalProof(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_WITHDRAWAL_PROOF); } function inRedeemed(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.REDEEMED); } function inCourtesyCall(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.COURTESY_CALL); } function inFraudLiquidationInProgress(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS); } function inLiquidationInProgress(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.LIQUIDATION_IN_PROGRESS); } function inLiquidated(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.LIQUIDATED); } function setAwaitingSignerSetup(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_SIGNER_SETUP); } function setAwaitingBTCFundingProof(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_BTC_FUNDING_PROOF); } function setFailedSetup(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.FAILED_SETUP); } function setActive(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.ACTIVE); } function setAwaitingWithdrawalSignature(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_WITHDRAWAL_SIGNATURE); } function setAwaitingWithdrawalProof(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_WITHDRAWAL_PROOF); } function setRedeemed(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.REDEEMED); } function setCourtesyCall(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.COURTESY_CALL); } function setFraudLiquidationInProgress(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS); } function setLiquidationInProgress(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.LIQUIDATION_IN_PROGRESS); } function setLiquidated(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.LIQUIDATED); } } pragma solidity 0.5.17; import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol"; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {DepositStates} from "./DepositStates.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {FeeRebateToken} from "../system/FeeRebateToken.sol"; library DepositUtils { using SafeMath for uint256; using SafeMath for uint64; using BytesLib for bytes; using BTCUtils for bytes; using BTCUtils for uint256; using ValidateSPV for bytes; using ValidateSPV for bytes32; using DepositStates for DepositUtils.Deposit; struct Deposit { // SET DURING CONSTRUCTION ITBTCSystem tbtcSystem; TBTCToken tbtcToken; IERC721 tbtcDepositToken; FeeRebateToken feeRebateToken; address vendingMachineAddress; uint64 lotSizeSatoshis; uint8 currentState; uint16 signerFeeDivisor; uint16 initialCollateralizedPercent; uint16 undercollateralizedThresholdPercent; uint16 severelyUndercollateralizedThresholdPercent; uint256 keepSetupFee; // SET ON FRAUD uint256 liquidationInitiated; // Timestamp of when liquidation starts uint256 courtesyCallInitiated; // When the courtesy call is issued address payable liquidationInitiator; // written when we request a keep address keepAddress; // The address of our keep contract uint256 signingGroupRequestedAt; // timestamp of signing group request // written when we get a keep result uint256 fundingProofTimerStart; // start of the funding proof period. reused for funding fraud proof period bytes32 signingGroupPubkeyX; // The X coordinate of the signing group's pubkey bytes32 signingGroupPubkeyY; // The Y coordinate of the signing group's pubkey // INITIALLY WRITTEN BY REDEMPTION FLOW address payable redeemerAddress; // The redeemer's address, used as fallback for fraud in redemption bytes redeemerOutputScript; // The redeemer output script uint256 initialRedemptionFee; // the initial fee as requested uint256 latestRedemptionFee; // the fee currently required by a redemption transaction uint256 withdrawalRequestTime; // the most recent withdrawal request timestamp bytes32 lastRequestedDigest; // the digest most recently requested for signing // written when we get funded bytes8 utxoValueBytes; // LE uint. the size of the deposit UTXO in satoshis uint256 fundedAt; // timestamp when funding proof was received bytes utxoOutpoint; // the 36-byte outpoint of the custodied UTXO /// @dev Map of ETH balances an address can withdraw after contract reaches ends-state. mapping(address => uint256) withdrawableAmounts; /// @dev Map of timestamps representing when transaction digests were approved for signing mapping (bytes32 => uint256) approvedDigests; } /// @notice Closes keep associated with the deposit. /// @dev Should be called when the keep is no longer needed and the signing /// group can disband. function closeKeep(DepositUtils.Deposit storage _d) internal { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.closeKeep(); } /// @notice Gets the current block difficulty. /// @dev Calls the light relay and gets the current block difficulty. /// @return The difficulty. function currentBlockDifficulty(Deposit storage _d) public view returns (uint256) { return _d.tbtcSystem.fetchRelayCurrentDifficulty(); } /// @notice Gets the previous block difficulty. /// @dev Calls the light relay and gets the previous block difficulty. /// @return The difficulty. function previousBlockDifficulty(Deposit storage _d) public view returns (uint256) { return _d.tbtcSystem.fetchRelayPreviousDifficulty(); } /// @notice Evaluates the header difficulties in a proof. /// @dev Uses the light oracle to source recent difficulty. /// @param _bitcoinHeaders The header chain to evaluate. /// @return True if acceptable, otherwise revert. function evaluateProofDifficulty(Deposit storage _d, bytes memory _bitcoinHeaders) public view { uint256 _reqDiff; uint256 _current = currentBlockDifficulty(_d); uint256 _previous = previousBlockDifficulty(_d); uint256 _firstHeaderDiff = _bitcoinHeaders.extractTarget().calculateDifficulty(); if (_firstHeaderDiff == _current) { _reqDiff = _current; } else if (_firstHeaderDiff == _previous) { _reqDiff = _previous; } else { revert("not at current or previous difficulty"); } uint256 _observedDiff = _bitcoinHeaders.validateHeaderChain(); require(_observedDiff != ValidateSPV.getErrBadLength(), "Invalid length of the headers chain"); require(_observedDiff != ValidateSPV.getErrInvalidChain(), "Invalid headers chain"); require(_observedDiff != ValidateSPV.getErrLowWork(), "Insufficient work in a header"); require( _observedDiff >= _reqDiff.mul(TBTCConstants.getTxProofDifficultyFactor()), "Insufficient accumulated difficulty in header chain" ); } /// @notice Syntactically check an SPV proof for a bitcoin transaction with its hash (ID). /// @dev Stateless SPV Proof verification documented elsewhere (see https://github.com/summa-tx/bitcoin-spv). /// @param _d Deposit storage pointer. /// @param _txId The bitcoin txid of the tx that is purportedly included in the header chain. /// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block. /// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed). /// @param _bitcoinHeaders An array of tightly-packed bitcoin headers. function checkProofFromTxId( Deposit storage _d, bytes32 _txId, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public view{ require( _txId.prove( _bitcoinHeaders.extractMerkleRootLE().toBytes32(), _merkleProof, _txIndexInBlock ), "Tx merkle proof is not valid for provided header and txId"); evaluateProofDifficulty(_d, _bitcoinHeaders); } /// @notice Find and validate funding output in transaction output vector using the index. /// @dev Gets `_fundingOutputIndex` output from the output vector and validates if it is /// a p2wpkh output with public key hash matching this deposit's public key hash. /// @param _d Deposit storage pointer. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC outputs. /// @param _fundingOutputIndex Index of funding output in _txOutputVector. /// @return Funding value. function findAndParseFundingOutput( DepositUtils.Deposit storage _d, bytes memory _txOutputVector, uint8 _fundingOutputIndex ) public view returns (bytes8) { bytes8 _valueBytes; bytes memory _output; // Find the output paying the signer PKH _output = _txOutputVector.extractOutputAtIndex(_fundingOutputIndex); require( keccak256(_output.extractHash()) == keccak256(abi.encodePacked(signerPKH(_d))), "Could not identify output funding the required public key hash" ); require( _output.length == 31 && _output.keccak256Slice(8, 23) == keccak256(abi.encodePacked(hex"160014", signerPKH(_d))), "Funding transaction output type unsupported: only p2wpkh outputs are supported" ); _valueBytes = bytes8(_output.slice(0, 8).toBytes32()); return _valueBytes; } /// @notice Validates the funding tx and parses information from it. /// @dev Takes a pre-parsed transaction and calculates values needed to verify funding. /// @param _d Deposit storage pointer. /// @param _txVersion Transaction version number (4-byte LE). /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first. /// @return The 8-byte LE UTXO size in satoshi, the 36byte outpoint. function validateAndParseFundingSPVProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public view returns (bytes8 _valueBytes, bytes memory _utxoOutpoint){ // not external to allow bytes memory parameters require(_txInputVector.validateVin(), "invalid input vector provided"); require(_txOutputVector.validateVout(), "invalid output vector provided"); bytes32 txID = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); _valueBytes = findAndParseFundingOutput(_d, _txOutputVector, _fundingOutputIndex); require(bytes8LEToUint(_valueBytes) >= _d.lotSizeSatoshis, "Deposit too small"); checkProofFromTxId(_d, txID, _merkleProof, _txIndexInBlock, _bitcoinHeaders); // The utxoOutpoint is the LE txID plus the index of the output as a 4-byte LE int // _fundingOutputIndex is a uint8, so we know it is only 1 byte // Therefore, pad with 3 more bytes _utxoOutpoint = abi.encodePacked(txID, _fundingOutputIndex, hex"000000"); } /// @notice Retreive the remaining term of the deposit /// @dev The return value is not guaranteed since block.timestmap can be lightly manipulated by miners. /// @return The remaining term of the deposit in seconds. 0 if already at term function remainingTerm(DepositUtils.Deposit storage _d) public view returns(uint256){ uint256 endOfTerm = _d.fundedAt.add(TBTCConstants.getDepositTerm()); if(block.timestamp < endOfTerm ) { return endOfTerm.sub(block.timestamp); } return 0; } /// @notice Calculates the amount of value at auction right now. /// @dev We calculate the % of the auction that has elapsed, then scale the value up. /// @param _d Deposit storage pointer. /// @return The value in wei to distribute in the auction at the current time. function auctionValue(Deposit storage _d) external view returns (uint256) { uint256 _elapsed = block.timestamp.sub(_d.liquidationInitiated); uint256 _available = address(this).balance; if (_elapsed > TBTCConstants.getAuctionDuration()) { return _available; } // This should make a smooth flow from base% to 100% uint256 _basePercentage = getAuctionBasePercentage(_d); uint256 _elapsedPercentage = uint256(100).sub(_basePercentage).mul(_elapsed).div(TBTCConstants.getAuctionDuration()); uint256 _percentage = _basePercentage.add(_elapsedPercentage); return _available.mul(_percentage).div(100); } /// @notice Gets the lot size in erc20 decimal places (max 18) /// @return uint256 lot size in 10**18 decimals. function lotSizeTbtc(Deposit storage _d) public view returns (uint256){ return _d.lotSizeSatoshis.mul(TBTCConstants.getSatoshiMultiplier()); } /// @notice Determines the fees due to the signers for work performed. /// @dev Signers are paid based on the TBTC issued. /// @return Accumulated fees in 10**18 decimals. function signerFeeTbtc(Deposit storage _d) public view returns (uint256) { return lotSizeTbtc(_d).div(_d.signerFeeDivisor); } /// @notice Determines the prefix to the compressed public key. /// @dev The prefix encodes the parity of the Y coordinate. /// @param _pubkeyY The Y coordinate of the public key. /// @return The 1-byte prefix for the compressed key. function determineCompressionPrefix(bytes32 _pubkeyY) public pure returns (bytes memory) { if(uint256(_pubkeyY) & 1 == 1) { return hex"03"; // Odd Y } else { return hex"02"; // Even Y } } /// @notice Compresses a public key. /// @dev Converts the 64-byte key to a 33-byte key, bitcoin-style. /// @param _pubkeyX The X coordinate of the public key. /// @param _pubkeyY The Y coordinate of the public key. /// @return The 33-byte compressed pubkey. function compressPubkey(bytes32 _pubkeyX, bytes32 _pubkeyY) public pure returns (bytes memory) { return abi.encodePacked(determineCompressionPrefix(_pubkeyY), _pubkeyX); } /// @notice Returns the packed public key (64 bytes) for the signing group. /// @dev We store it as 2 bytes32, (2 slots) then repack it on demand. /// @return 64 byte public key. function signerPubkey(Deposit storage _d) external view returns (bytes memory) { return abi.encodePacked(_d.signingGroupPubkeyX, _d.signingGroupPubkeyY); } /// @notice Returns the Bitcoin pubkeyhash (hash160) for the signing group. /// @dev This is used in bitcoin output scripts for the signers. /// @return 20-bytes public key hash. function signerPKH(Deposit storage _d) public view returns (bytes20) { bytes memory _pubkey = compressPubkey(_d.signingGroupPubkeyX, _d.signingGroupPubkeyY); bytes memory _digest = _pubkey.hash160(); return bytes20(_digest.toAddress(0)); // dirty solidity hack } /// @notice Returns the size of the deposit UTXO in satoshi. /// @dev We store the deposit as bytes8 to make signature checking easier. /// @return UTXO value in satoshi. function utxoValue(Deposit storage _d) external view returns (uint256) { return bytes8LEToUint(_d.utxoValueBytes); } /// @notice Gets the current price of Bitcoin in Ether. /// @dev Polls the price feed via the system contract. /// @return The current price of 1 sat in wei. function fetchBitcoinPrice(Deposit storage _d) external view returns (uint256) { return _d.tbtcSystem.fetchBitcoinPrice(); } /// @notice Fetches the Keep's bond amount in wei. /// @dev Calls the keep contract to do so. /// @return The amount of bonded ETH in wei. function fetchBondAmount(Deposit storage _d) external view returns (uint256) { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); return _keep.checkBondAmount(); } /// @notice Convert a LE bytes8 to a uint256. /// @dev Do this by converting to bytes, then reversing endianness, then converting to int. /// @return The uint256 represented in LE by the bytes8. function bytes8LEToUint(bytes8 _b) public pure returns (uint256) { return abi.encodePacked(_b).reverseEndianness().bytesToUint(); } /// @notice Gets timestamp of digest approval for signing. /// @dev Identifies entry in the recorded approvals by keep ID and digest pair. /// @param _digest Digest to check approval for. /// @return Timestamp from the moment of recording the digest for signing. /// Returns 0 if the digest was not approved for signing. function wasDigestApprovedForSigning(Deposit storage _d, bytes32 _digest) external view returns (uint256) { return _d.approvedDigests[_digest]; } /// @notice Looks up the Fee Rebate Token holder. /// @return The current token holder if the Token exists. /// address(0) if the token does not exist. function feeRebateTokenHolder(Deposit storage _d) public view returns (address payable) { address tokenHolder = address(0); if(_d.feeRebateToken.exists(uint256(address(this)))){ tokenHolder = address(uint160(_d.feeRebateToken.ownerOf(uint256(address(this))))); } return address(uint160(tokenHolder)); } /// @notice Looks up the deposit beneficiary by calling the tBTC system. /// @dev We cast the address to a uint256 to match the 721 standard. /// @return The current deposit beneficiary. function depositOwner(Deposit storage _d) public view returns (address payable) { return address(uint160(_d.tbtcDepositToken.ownerOf(uint256(address(this))))); } /// @notice Deletes state after termination of redemption process. /// @dev We keep around the redeemer address so we can pay them out. function redemptionTeardown(Deposit storage _d) public { _d.redeemerOutputScript = ""; _d.initialRedemptionFee = 0; _d.withdrawalRequestTime = 0; _d.lastRequestedDigest = bytes32(0); } /// @notice Get the starting percentage of the bond at auction. /// @dev This will return the same value regardless of collateral price. /// @return The percentage of the InitialCollateralizationPercent that will result /// in a 100% bond value base auction given perfect collateralization. function getAuctionBasePercentage(Deposit storage _d) internal view returns (uint256) { return uint256(10000).div(_d.initialCollateralizedPercent); } /// @notice Seize the signer bond from the keep contract. /// @dev we check our balance before and after. /// @return The amount seized in wei. function seizeSignerBonds(Deposit storage _d) internal returns (uint256) { uint256 _preCallBalance = address(this).balance; IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.seizeSignerBonds(); uint256 _postCallBalance = address(this).balance; require(_postCallBalance > _preCallBalance, "No funds received, unexpected"); return _postCallBalance.sub(_preCallBalance); } /// @notice Adds a given amount to the withdraw allowance for the address. /// @dev Withdrawals can only happen when a contract is in an end-state. function enableWithdrawal(DepositUtils.Deposit storage _d, address _withdrawer, uint256 _amount) internal { _d.withdrawableAmounts[_withdrawer] = _d.withdrawableAmounts[_withdrawer].add(_amount); } /// @notice Withdraw caller's allowance. /// @dev Withdrawals can only happen when a contract is in an end-state. function withdrawFunds(DepositUtils.Deposit storage _d) internal { uint256 available = _d.withdrawableAmounts[msg.sender]; require(_d.inEndState(), "Contract not yet terminated"); require(available > 0, "Nothing to withdraw"); require(address(this).balance >= available, "Insufficient contract balance"); // zero-out to prevent reentrancy _d.withdrawableAmounts[msg.sender] = 0; /* solium-disable-next-line security/no-call-value */ (bool ok,) = msg.sender.call.value(available)(""); require( ok, "Failed to send withdrawable amount to sender" ); } /// @notice Get the caller's withdraw allowance. /// @return The caller's withdraw allowance in wei. function getWithdrawableAmount(DepositUtils.Deposit storage _d) internal view returns (uint256) { return _d.withdrawableAmounts[msg.sender]; } /// @notice Distributes the fee rebate to the Fee Rebate Token owner. /// @dev Whenever this is called we are shutting down. function distributeFeeRebate(Deposit storage _d) internal { address rebateTokenHolder = feeRebateTokenHolder(_d); // exit the function if there is nobody to send the rebate to if(rebateTokenHolder == address(0)){ return; } // pay out the rebate if it is available if(_d.tbtcToken.balanceOf(address(this)) >= signerFeeTbtc(_d)) { _d.tbtcToken.transfer(rebateTokenHolder, signerFeeTbtc(_d)); } } /// @notice Pushes ether held by the deposit to the signer group. /// @dev Ether is returned to signing group members bonds. /// @param _ethValue The amount of ether to send. function pushFundsToKeepGroup(Deposit storage _d, uint256 _ethValue) internal { require(address(this).balance >= _ethValue, "Not enough funds to send"); if(_ethValue > 0){ IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.returnPartialSignerBonds.value(_ethValue)(); } } /// @notice Calculate TBTC amount required for redemption by a specified /// _redeemer. If _assumeRedeemerHoldTdt is true, return the /// requirement as if the redeemer holds this deposit's TDT. /// @dev Will revert if redemption is not possible by the current owner and /// _assumeRedeemerHoldsTdt was not set. Setting /// _assumeRedeemerHoldsTdt only when appropriate is the responsibility /// of the caller; as such, this function should NEVER be publicly /// exposed. /// @param _redeemer The account that should be treated as redeeming this /// deposit for the purposes of this calculation. /// @param _assumeRedeemerHoldsTdt If true, the calculation assumes that the /// specified redeemer holds the TDT. If false, the calculation /// checks the deposit owner against the specified _redeemer. Note /// that this parameter should be false for all mutating calls to /// preserve system correctness. /// @return A tuple of the amount the redeemer owes to the deposit to /// initiate redemption, the amount that is owed to the TDT holder /// when redemption is initiated, and the amount that is owed to the /// FRT holder when redemption is initiated. function calculateRedemptionTbtcAmounts( DepositUtils.Deposit storage _d, address _redeemer, bool _assumeRedeemerHoldsTdt ) internal view returns ( uint256 owedToDeposit, uint256 owedToTdtHolder, uint256 owedToFrtHolder ) { bool redeemerHoldsTdt = _assumeRedeemerHoldsTdt || depositOwner(_d) == _redeemer; bool preTerm = remainingTerm(_d) > 0 && !_d.inCourtesyCall(); require( redeemerHoldsTdt || !preTerm, "Only TDT holder can redeem unless deposit is at-term or in COURTESY_CALL" ); bool frtExists = feeRebateTokenHolder(_d) != address(0); bool redeemerHoldsFrt = feeRebateTokenHolder(_d) == _redeemer; uint256 signerFee = signerFeeTbtc(_d); uint256 feeEscrow = calculateRedemptionFeeEscrow( signerFee, preTerm, frtExists, redeemerHoldsTdt, redeemerHoldsFrt ); // Base redemption + fee = total we need to have escrowed to start // redemption. owedToDeposit = calculateBaseRedemptionCharge( lotSizeTbtc(_d), redeemerHoldsTdt ).add(feeEscrow); // Adjust the amount owed to the deposit based on any balance the // deposit already has. uint256 balance = _d.tbtcToken.balanceOf(address(this)); if (owedToDeposit > balance) { owedToDeposit = owedToDeposit.sub(balance); } else { owedToDeposit = 0; } // Pre-term, the FRT rebate is payed out, but if the redeemer holds the // FRT, the amount has already been subtracted from what is owed to the // deposit at this point (by calculateRedemptionFeeEscrow). This allows // the redeemer to simply *not pay* the fee rebate, rather than having // them pay it only to have it immediately returned. if (preTerm && frtExists && !redeemerHoldsFrt) { owedToFrtHolder = signerFee; } // The TDT holder gets any leftover balance. owedToTdtHolder = balance.add(owedToDeposit).sub(signerFee).sub(owedToFrtHolder); return (owedToDeposit, owedToTdtHolder, owedToFrtHolder); } /// @notice Get the base TBTC amount needed to redeem. /// @param _lotSize The lot size to use for the base redemption charge. /// @param _redeemerHoldsTdt True if the redeemer is the TDT holder. /// @return The amount in TBTC. function calculateBaseRedemptionCharge( uint256 _lotSize, bool _redeemerHoldsTdt ) internal pure returns (uint256){ if (_redeemerHoldsTdt) { return 0; } return _lotSize; } /// @notice Get fees owed for redemption /// @param signerFee The value of the signer fee for fee calculations. /// @param _preTerm True if the Deposit is at-term or in courtesy_call. /// @param _frtExists True if the FRT exists. /// @param _redeemerHoldsTdt True if the the redeemer holds the TDT. /// @param _redeemerHoldsFrt True if the redeemer holds the FRT. /// @return The fees owed in TBTC. function calculateRedemptionFeeEscrow( uint256 signerFee, bool _preTerm, bool _frtExists, bool _redeemerHoldsTdt, bool _redeemerHoldsFrt ) internal pure returns (uint256) { // Escrow the fee rebate so the FRT holder can be repaids, unless the // redeemer holds the FRT, in which case we simply don't require the // rebate from them. bool escrowRequiresFeeRebate = _preTerm && _frtExists && ! _redeemerHoldsFrt; bool escrowRequiresFee = _preTerm || // If the FRT exists at term/courtesy call, the fee is // "required", but should already be escrowed before redemption. _frtExists || // The TDT holder always owes fees if there is no FRT. _redeemerHoldsTdt; uint256 feeEscrow = 0; if (escrowRequiresFee) { feeEscrow += signerFee; } if (escrowRequiresFeeRebate) { feeEscrow += signerFee; } return feeEscrow; } } pragma solidity 0.5.17; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositLiquidation} from "./DepositLiquidation.sol"; import {DepositStates} from "./DepositStates.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; library DepositFunding { using SafeMath for uint256; using SafeMath for uint64; using BTCUtils for bytes; using BytesLib for bytes; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Deletes state after funding. /// @dev This is called when we go to ACTIVE or setup fails without fraud. function fundingTeardown(DepositUtils.Deposit storage _d) internal { _d.signingGroupRequestedAt = 0; _d.fundingProofTimerStart = 0; } /// @notice Deletes state after the funding ECDSA fraud process. /// @dev This is only called as we transition to setup failed. function fundingFraudTeardown(DepositUtils.Deposit storage _d) internal { _d.keepAddress = address(0); _d.signingGroupRequestedAt = 0; _d.fundingProofTimerStart = 0; _d.signingGroupPubkeyX = bytes32(0); _d.signingGroupPubkeyY = bytes32(0); } /// @notice Internally called function to set up a newly created Deposit /// instance. This should not be called by developers, use /// `DepositFactory.createDeposit` to create a new deposit. /// @dev If called directly, the transaction will revert since the call will /// be executed on an already set-up instance. /// @param _d Deposit storage pointer. /// @param _lotSizeSatoshis Lot size in satoshis. function initialize( DepositUtils.Deposit storage _d, uint64 _lotSizeSatoshis ) public { require(_d.tbtcSystem.getAllowNewDeposits(), "New deposits aren't allowed."); require(_d.inStart(), "Deposit setup already requested"); _d.lotSizeSatoshis = _lotSizeSatoshis; _d.keepSetupFee = _d.tbtcSystem.getNewDepositFeeEstimate(); // Note: this is a library, and library functions cannot be marked as // payable. Thus, we disable Solium's check that msg.value can only be // used in a payable function---this restriction actually applies to the // caller of this `initialize` function, Deposit.initializeDeposit. /* solium-disable-next-line value-in-payable */ _d.keepAddress = _d.tbtcSystem.requestNewKeep.value(msg.value)( _lotSizeSatoshis, TBTCConstants.getDepositTerm() ); require(_d.fetchBondAmount() >= _d.keepSetupFee, "Insufficient signer bonds to cover setup fee"); _d.signerFeeDivisor = _d.tbtcSystem.getSignerFeeDivisor(); _d.undercollateralizedThresholdPercent = _d.tbtcSystem.getUndercollateralizedThresholdPercent(); _d.severelyUndercollateralizedThresholdPercent = _d.tbtcSystem.getSeverelyUndercollateralizedThresholdPercent(); _d.initialCollateralizedPercent = _d.tbtcSystem.getInitialCollateralizedPercent(); _d.signingGroupRequestedAt = block.timestamp; _d.setAwaitingSignerSetup(); _d.logCreated(_d.keepAddress); } /// @notice Anyone may notify the contract that signing group setup has timed out. /// @param _d Deposit storage pointer. function notifySignerSetupFailed(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingSignerSetup(), "Not awaiting setup"); require( block.timestamp > _d.signingGroupRequestedAt.add(TBTCConstants.getSigningGroupFormationTimeout()), "Signing group formation timeout not yet elapsed" ); // refund the deposit owner the cost to create a new Deposit at the time the Deposit was opened. uint256 _seized = _d.seizeSignerBonds(); if(_seized >= _d.keepSetupFee){ /* solium-disable-next-line security/no-send */ _d.enableWithdrawal(_d.depositOwner(), _d.keepSetupFee); _d.pushFundsToKeepGroup(_seized.sub(_d.keepSetupFee)); } _d.setFailedSetup(); _d.logSetupFailed(); fundingTeardown(_d); } /// @notice we poll the Keep contract to retrieve our pubkey. /// @dev We store the pubkey as 2 bytestrings, X and Y. /// @param _d Deposit storage pointer. /// @return True if successful, otherwise revert. function retrieveSignerPubkey(DepositUtils.Deposit storage _d) public { require(_d.inAwaitingSignerSetup(), "Not currently awaiting signer setup"); bytes memory _publicKey = IBondedECDSAKeep(_d.keepAddress).getPublicKey(); require(_publicKey.length == 64, "public key not set or not 64-bytes long"); _d.signingGroupPubkeyX = _publicKey.slice(0, 32).toBytes32(); _d.signingGroupPubkeyY = _publicKey.slice(32, 32).toBytes32(); require(_d.signingGroupPubkeyY != bytes32(0) && _d.signingGroupPubkeyX != bytes32(0), "Keep returned bad pubkey"); _d.fundingProofTimerStart = block.timestamp; _d.setAwaitingBTCFundingProof(); _d.logRegisteredPubkey( _d.signingGroupPubkeyX, _d.signingGroupPubkeyY); } /// @notice Anyone may notify the contract that the funder has failed to /// prove that they have sent BTC in time. /// @dev This is considered a funder fault, and the funder's payment for /// opening the deposit is not refunded. Reverts if the funding timeout /// has not yet elapsed, or if the deposit is not currently awaiting /// funding proof. /// @param _d Deposit storage pointer. function notifyFundingTimedOut(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingBTCFundingProof(), "Funding timeout has not started"); require( block.timestamp > _d.fundingProofTimerStart.add(TBTCConstants.getFundingTimeout()), "Funding timeout has not elapsed." ); _d.setFailedSetup(); _d.logSetupFailed(); _d.closeKeep(); fundingTeardown(_d); } /// @notice Requests a funder abort for a failed-funding deposit; that is, /// requests return of a sent UTXO to `_abortOutputScript`. This can /// be used for example when a UTXO is sent that is the wrong size /// for the lot. Must be called after setup fails for any reason, /// and imposes no requirement or incentive on the signing group to /// return the UTXO. /// @dev This is a self-admitted funder fault, and should only be callable /// by the TDT holder. /// @param _d Deposit storage pointer. /// @param _abortOutputScript The output script the funder wishes to request /// a return of their UTXO to. function requestFunderAbort( DepositUtils.Deposit storage _d, bytes memory _abortOutputScript ) public { // not external to allow bytes memory parameters require( _d.inFailedSetup(), "The deposit has not failed funding" ); _d.logFunderRequestedAbort(_abortOutputScript); } /// @notice Anyone can provide a signature that was not requested to prove fraud during funding. /// @dev Calls out to the keep to verify if there was fraud. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. /// @return True if successful, otherwise revert. function provideFundingECDSAFraudProof( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters require( _d.inAwaitingBTCFundingProof(), "Signer fraud during funding flow only available while awaiting funding" ); _d.submitSignatureFraud(_v, _r, _s, _signedDigest, _preimage); _d.logFraudDuringSetup(); // Allow deposit owner to withdraw seized bonds after contract termination. uint256 _seized = _d.seizeSignerBonds(); _d.enableWithdrawal(_d.depositOwner(), _seized); fundingFraudTeardown(_d); _d.setFailedSetup(); _d.logSetupFailed(); } /// @notice Anyone may notify the deposit of a funding proof to activate the deposit. /// This is the happy-path of the funding flow. It means that we have succeeded. /// @dev Takes a pre-parsed transaction and calculates values needed to verify funding. /// @param _d Deposit storage pointer. /// @param _txVersion Transaction version number (4-byte LE). /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first. function provideBTCFundingProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters require(_d.inAwaitingBTCFundingProof(), "Not awaiting funding"); bytes8 _valueBytes; bytes memory _utxoOutpoint; (_valueBytes, _utxoOutpoint) = _d.validateAndParseFundingSPVProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); // Write down the UTXO info and set to active. Congratulations :) _d.utxoValueBytes = _valueBytes; _d.utxoOutpoint = _utxoOutpoint; _d.fundedAt = block.timestamp; bytes32 _txid = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); fundingTeardown(_d); _d.setActive(); _d.logFunded(_txid); } } pragma solidity 0.5.17; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol"; import {CheckBitcoinSigs} from "@summa-tx/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositStates} from "./DepositStates.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {DepositLiquidation} from "./DepositLiquidation.sol"; library DepositRedemption { using SafeMath for uint256; using CheckBitcoinSigs for bytes; using BytesLib for bytes; using BTCUtils for bytes; using ValidateSPV for bytes; using ValidateSPV for bytes32; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Pushes signer fee to the Keep group by transferring it to the Keep address. /// @dev Approves the keep contract, then expects it to call transferFrom. function distributeSignerFee(DepositUtils.Deposit storage _d) internal { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _d.tbtcToken.approve(_d.keepAddress, _d.signerFeeTbtc()); _keep.distributeERC20Reward(address(_d.tbtcToken), _d.signerFeeTbtc()); } /// @notice Approves digest for signing by a keep. /// @dev Calls given keep to sign the digest. Records a current timestamp /// for given digest. /// @param _digest Digest to approve. function approveDigest(DepositUtils.Deposit storage _d, bytes32 _digest) internal { IBondedECDSAKeep(_d.keepAddress).sign(_digest); _d.approvedDigests[_digest] = block.timestamp; } /// @notice Handles TBTC requirements for redemption. /// @dev Burns or transfers depending on term and supply-peg impact. /// Once these transfers complete, the deposit balance should be /// sufficient to pay out signer fees once the redemption transaction /// is proven on the Bitcoin side. function performRedemptionTbtcTransfers(DepositUtils.Deposit storage _d) internal { address tdtHolder = _d.depositOwner(); address frtHolder = _d.feeRebateTokenHolder(); address vendingMachineAddress = _d.vendingMachineAddress; ( uint256 tbtcOwedToDeposit, uint256 tbtcOwedToTdtHolder, uint256 tbtcOwedToFrtHolder ) = _d.calculateRedemptionTbtcAmounts(_d.redeemerAddress, false); if(tbtcOwedToDeposit > 0){ _d.tbtcToken.transferFrom(msg.sender, address(this), tbtcOwedToDeposit); } if(tbtcOwedToTdtHolder > 0){ if(tdtHolder == vendingMachineAddress){ _d.tbtcToken.burn(tbtcOwedToTdtHolder); } else { _d.tbtcToken.transfer(tdtHolder, tbtcOwedToTdtHolder); } } if(tbtcOwedToFrtHolder > 0){ _d.tbtcToken.transfer(frtHolder, tbtcOwedToFrtHolder); } } function _requestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _redeemer ) internal { require(_d.inRedeemableState(), "Redemption only available from Active or Courtesy state"); bytes memory _output = abi.encodePacked(_outputValueBytes, _redeemerOutputScript); require(_output.extractHash().length > 0, "Output script must be a standard type"); // set redeemerAddress early to enable direct access by other functions _d.redeemerAddress = _redeemer; performRedemptionTbtcTransfers(_d); // Convert the 8-byte LE ints to uint256 uint256 _outputValue = abi.encodePacked(_outputValueBytes).reverseEndianness().bytesToUint(); uint256 _requestedFee = _d.utxoValue().sub(_outputValue); require(_requestedFee >= TBTCConstants.getMinimumRedemptionFee(), "Fee is too low"); require( _requestedFee < _d.utxoValue() / 2, "Initial fee cannot exceed half of the deposit's value" ); // Calculate the sighash bytes32 _sighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoValueBytes, _outputValueBytes, _redeemerOutputScript); // write all request details _d.redeemerOutputScript = _redeemerOutputScript; _d.initialRedemptionFee = _requestedFee; _d.latestRedemptionFee = _requestedFee; _d.withdrawalRequestTime = block.timestamp; _d.lastRequestedDigest = _sighash; approveDigest(_d, _sighash); _d.setAwaitingWithdrawalSignature(); _d.logRedemptionRequested( _redeemer, _sighash, _d.utxoValue(), _redeemerOutputScript, _requestedFee, _d.utxoOutpoint); } /// @notice Anyone can request redemption as long as they can. /// approve the TDT transfer to the final recipient. /// @dev The redeemer specifies details about the Bitcoin redemption tx and pays for the redemption /// on behalf of _finalRecipient. /// @param _d Deposit storage pointer. /// @param _outputValueBytes The 8-byte LE output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer. function transferAndRequestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _finalRecipient ) public { // not external to allow bytes memory parameters _d.tbtcDepositToken.transferFrom(msg.sender, _finalRecipient, uint256(address(this))); _requestRedemption(_d, _outputValueBytes, _redeemerOutputScript, _finalRecipient); } /// @notice Only TDT holder can request redemption, /// unless Deposit is expired or in COURTESY_CALL. /// @dev The redeemer specifies details about the Bitcoin redemption transaction. /// @param _d Deposit storage pointer. /// @param _outputValueBytes The 8-byte LE output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. function requestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters _requestRedemption(_d, _outputValueBytes, _redeemerOutputScript, msg.sender); } /// @notice Anyone may provide a withdrawal signature if it was requested. /// @dev The signers will be penalized if this (or provideRedemptionProof) is not called. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. Should be in the low half of secp256k1 curve's order. function provideRedemptionSignature( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s ) external { require(_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature"); // If we're outside of the signature window, we COULD punish signers here // Instead, we consider this a no-harm-no-foul situation. // The signers have not stolen funds. Most likely they've just inconvenienced someone // Validate `s` value for a malleability concern described in EIP-2. // Only signatures with `s` value in the lower half of the secp256k1 // curve's order are considered valid. require( uint256(_s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "Malleable signature - s should be in the low half of secp256k1 curve's order" ); // The signature must be valid on the pubkey require( _d.signerPubkey().checkSig( _d.lastRequestedDigest, _v, _r, _s ), "Invalid signature" ); // A signature has been provided, now we wait for fee bump or redemption _d.setAwaitingWithdrawalProof(); _d.logGotRedemptionSignature( _d.lastRequestedDigest, _r, _s); } /// @notice Anyone may notify the contract that a fee bump is needed. /// @dev This sends us back to AWAITING_WITHDRAWAL_SIGNATURE. /// @param _d Deposit storage pointer. /// @param _previousOutputValueBytes The previous output's value. /// @param _newOutputValueBytes The new output's value. function increaseRedemptionFee( DepositUtils.Deposit storage _d, bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) public { require(_d.inAwaitingWithdrawalProof(), "Fee increase only available after signature provided"); require(block.timestamp >= _d.withdrawalRequestTime.add(TBTCConstants.getIncreaseFeeTimer()), "Fee increase not yet permitted"); uint256 _newOutputValue = checkRelationshipToPrevious(_d, _previousOutputValueBytes, _newOutputValueBytes); // If the fee bump shrinks the UTXO value below the minimum allowed // value, clamp it to that minimum. Further fee bumps will be disallowed // by checkRelationshipToPrevious. if (_newOutputValue < TBTCConstants.getMinimumUtxoValue()) { _newOutputValue = TBTCConstants.getMinimumUtxoValue(); } _d.latestRedemptionFee = _d.utxoValue().sub(_newOutputValue); // Calculate the next sighash bytes32 _sighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoValueBytes, _newOutputValueBytes, _d.redeemerOutputScript); // Ratchet the signature and redemption proof timeouts _d.withdrawalRequestTime = block.timestamp; _d.lastRequestedDigest = _sighash; approveDigest(_d, _sighash); // Go back to waiting for a signature _d.setAwaitingWithdrawalSignature(); _d.logRedemptionRequested( msg.sender, _sighash, _d.utxoValue(), _d.redeemerOutputScript, _d.latestRedemptionFee, _d.utxoOutpoint); } function checkRelationshipToPrevious( DepositUtils.Deposit storage _d, bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) public view returns (uint256 _newOutputValue){ // Check that we're incrementing the fee by exactly the redeemer's initial fee uint256 _previousOutputValue = DepositUtils.bytes8LEToUint(_previousOutputValueBytes); _newOutputValue = DepositUtils.bytes8LEToUint(_newOutputValueBytes); require(_previousOutputValue.sub(_newOutputValue) == _d.initialRedemptionFee, "Not an allowed fee step"); // Calculate the previous one so we can check that it really is the previous one bytes32 _previousSighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoValueBytes, _previousOutputValueBytes, _d.redeemerOutputScript); require( _d.wasDigestApprovedForSigning(_previousSighash) == _d.withdrawalRequestTime, "Provided previous value does not yield previous sighash" ); } /// @notice Anyone may provide a withdrawal proof to prove redemption. /// @dev The signers will be penalized if this is not called. /// @param _d Deposit storage pointer. /// @param _txVersion Transaction version number (4-byte LE). /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block. /// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed). /// @param _bitcoinHeaders An array of tightly-packed bitcoin headers. function provideRedemptionProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters bytes32 _txid; uint256 _fundingOutputValue; require(_d.inRedemption(), "Redemption proof only allowed from redemption flow"); _fundingOutputValue = redemptionTransactionChecks(_d, _txInputVector, _txOutputVector); _txid = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); _d.checkProofFromTxId(_txid, _merkleProof, _txIndexInBlock, _bitcoinHeaders); require((_d.utxoValue().sub(_fundingOutputValue)) <= _d.latestRedemptionFee, "Incorrect fee amount"); // Transfer TBTC to signers and close the keep. distributeSignerFee(_d); _d.closeKeep(); _d.distributeFeeRebate(); // We're done yey! _d.setRedeemed(); _d.redemptionTeardown(); _d.logRedeemed(_txid); } /// @notice Check the redemption transaction input and output vector to ensure the transaction spends /// the correct UTXO and sends value to the appropriate public key hash. /// @dev We only look at the first input and first output. Revert if we find the wrong UTXO or value recipient. /// It's safe to look at only the first input/output as anything that breaks this can be considered fraud /// and can be caught by ECDSAFraudProof. /// @param _d Deposit storage pointer. /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @return The value sent to the redeemer's public key hash. function redemptionTransactionChecks( DepositUtils.Deposit storage _d, bytes memory _txInputVector, bytes memory _txOutputVector ) public view returns (uint256) { require(_txInputVector.validateVin(), "invalid input vector provided"); require(_txOutputVector.validateVout(), "invalid output vector provided"); bytes memory _input = _txInputVector.slice(1, _txInputVector.length-1); require( keccak256(_input.extractOutpoint()) == keccak256(_d.utxoOutpoint), "Tx spends the wrong UTXO" ); bytes memory _output = _txOutputVector.slice(1, _txOutputVector.length-1); bytes memory _expectedOutputScript = _d.redeemerOutputScript; require(_output.length - 8 >= _d.redeemerOutputScript.length, "Output script is too short to extract the expected script"); require( keccak256(_output.slice(8, _expectedOutputScript.length)) == keccak256(_expectedOutputScript), "Tx sends value to wrong output script" ); return (uint256(_output.extractValue())); } /// @notice Anyone may notify the contract that the signers have failed to produce a signature. /// @dev This is considered fraud, and is punished. /// @param _d Deposit storage pointer. function notifyRedemptionSignatureTimedOut(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature"); require(block.timestamp > _d.withdrawalRequestTime.add(TBTCConstants.getSignatureTimeout()), "Signature timer has not elapsed"); _d.startLiquidation(false); // not fraud, just failure } /// @notice Anyone may notify the contract that the signers have failed to produce a redemption proof. /// @dev This is considered fraud, and is punished. /// @param _d Deposit storage pointer. function notifyRedemptionProofTimedOut(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingWithdrawalProof(), "Not currently awaiting a redemption proof"); require(block.timestamp > _d.withdrawalRequestTime.add(TBTCConstants.getRedemptionProofTimeout()), "Proof timer has not elapsed"); _d.startLiquidation(false); // not fraud, just failure } } pragma solidity 0.5.17; library TBTCConstants { // This is intended to make it easy to update system params // During testing swap this out with another constats contract // System Parameters uint256 public constant BENEFICIARY_FEE_DIVISOR = 1000; // 1/1000 = 10 bps = 0.1% = 0.001 uint256 public constant SATOSHI_MULTIPLIER = 10 ** 10; // multiplier to convert satoshi to TBTC token units uint256 public constant DEPOSIT_TERM_LENGTH = 180 * 24 * 60 * 60; // 180 days in seconds uint256 public constant TX_PROOF_DIFFICULTY_FACTOR = 6; // confirmations on the Bitcoin chain // Redemption Flow uint256 public constant REDEMPTION_SIGNATURE_TIMEOUT = 2 * 60 * 60; // seconds uint256 public constant INCREASE_FEE_TIMER = 4 * 60 * 60; // seconds uint256 public constant REDEMPTION_PROOF_TIMEOUT = 6 * 60 * 60; // seconds uint256 public constant MINIMUM_REDEMPTION_FEE = 2000; // satoshi uint256 public constant MINIMUM_UTXO_VALUE = 2000; // satoshi // Funding Flow uint256 public constant FUNDING_PROOF_TIMEOUT = 3 * 60 * 60; // seconds uint256 public constant FORMATION_TIMEOUT = 3 * 60 * 60; // seconds // Liquidation Flow uint256 public constant COURTESY_CALL_DURATION = 6 * 60 * 60; // seconds uint256 public constant AUCTION_DURATION = 24 * 60 * 60; // seconds // Getters for easy access function getBeneficiaryRewardDivisor() external pure returns (uint256) { return BENEFICIARY_FEE_DIVISOR; } function getSatoshiMultiplier() external pure returns (uint256) { return SATOSHI_MULTIPLIER; } function getDepositTerm() external pure returns (uint256) { return DEPOSIT_TERM_LENGTH; } function getTxProofDifficultyFactor() external pure returns (uint256) { return TX_PROOF_DIFFICULTY_FACTOR; } function getSignatureTimeout() external pure returns (uint256) { return REDEMPTION_SIGNATURE_TIMEOUT; } function getIncreaseFeeTimer() external pure returns (uint256) { return INCREASE_FEE_TIMER; } function getRedemptionProofTimeout() external pure returns (uint256) { return REDEMPTION_PROOF_TIMEOUT; } function getMinimumRedemptionFee() external pure returns (uint256) { return MINIMUM_REDEMPTION_FEE; } function getMinimumUtxoValue() external pure returns (uint256) { return MINIMUM_UTXO_VALUE; } function getFundingTimeout() external pure returns (uint256) { return FUNDING_PROOF_TIMEOUT; } function getSigningGroupFormationTimeout() external pure returns (uint256) { return FORMATION_TIMEOUT; } function getCourtesyCallTimeout() external pure returns (uint256) { return COURTESY_CALL_DURATION; } function getAuctionDuration() external pure returns (uint256) { return AUCTION_DURATION; } } pragma solidity 0.5.17; import {DepositLog} from "../DepositLog.sol"; import {DepositUtils} from "./DepositUtils.sol"; library OutsourceDepositLogging { /// @notice Fires a Created event. /// @dev `DepositLog.logCreated` fires a Created event with /// _keepAddress, msg.sender and block.timestamp. /// msg.sender will be the calling Deposit's address. /// @param _keepAddress The address of the associated keep. function logCreated(DepositUtils.Deposit storage _d, address _keepAddress) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logCreated(_keepAddress); } /// @notice Fires a RedemptionRequested event. /// @dev This is the only event without an explicit timestamp. /// @param _redeemer The ethereum address of the redeemer. /// @param _digest The calculated sighash digest. /// @param _utxoValue The size of the utxo in sat. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _requestedFee The redeemer or bump-system specified fee. /// @param _outpoint The 36 byte outpoint. /// @return True if successful, else revert. function logRedemptionRequested( DepositUtils.Deposit storage _d, address _redeemer, bytes32 _digest, uint256 _utxoValue, bytes memory _redeemerOutputScript, uint256 _requestedFee, bytes memory _outpoint ) public { // not external to allow bytes memory parameters DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logRedemptionRequested( _redeemer, _digest, _utxoValue, _redeemerOutputScript, _requestedFee, _outpoint ); } /// @notice Fires a GotRedemptionSignature event. /// @dev We append the sender, which is the deposit contract that called. /// @param _digest Signed digest. /// @param _r Signature r value. /// @param _s Signature s value. /// @return True if successful, else revert. function logGotRedemptionSignature( DepositUtils.Deposit storage _d, bytes32 _digest, bytes32 _r, bytes32 _s ) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logGotRedemptionSignature( _digest, _r, _s ); } /// @notice Fires a RegisteredPubkey event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logRegisteredPubkey( DepositUtils.Deposit storage _d, bytes32 _signingGroupPubkeyX, bytes32 _signingGroupPubkeyY ) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logRegisteredPubkey( _signingGroupPubkeyX, _signingGroupPubkeyY); } /// @notice Fires a SetupFailed event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logSetupFailed(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logSetupFailed(); } /// @notice Fires a FunderAbortRequested event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logFunderRequestedAbort( DepositUtils.Deposit storage _d, bytes memory _abortOutputScript ) public { // not external to allow bytes memory parameters DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logFunderRequestedAbort(_abortOutputScript); } /// @notice Fires a FraudDuringSetup event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logFraudDuringSetup(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logFraudDuringSetup(); } /// @notice Fires a Funded event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logFunded(DepositUtils.Deposit storage _d, bytes32 _txid) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logFunded(_txid); } /// @notice Fires a CourtesyCalled event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logCourtesyCalled(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logCourtesyCalled(); } /// @notice Fires a StartedLiquidation event. /// @dev We append the sender, which is the deposit contract that called. /// @param _wasFraud True if liquidating for fraud. function logStartedLiquidation(DepositUtils.Deposit storage _d, bool _wasFraud) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logStartedLiquidation(_wasFraud); } /// @notice Fires a Redeemed event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logRedeemed(DepositUtils.Deposit storage _d, bytes32 _txid) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logRedeemed(_txid); } /// @notice Fires a Liquidated event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logLiquidated(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logLiquidated(); } /// @notice Fires a ExitedCourtesyCall event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logExitedCourtesyCall(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logExitedCourtesyCall(); } } pragma solidity 0.5.17; import {TBTCDepositToken} from "./system/TBTCDepositToken.sol"; // solium-disable function-order // Below, a few functions must be public to allow bytes memory parameters, but // their being so triggers errors because public functions should be grouped // below external functions. Since these would be external if it were possible, // we ignore the issue. contract DepositLog { /* Logging philosophy: Every state transition should fire a log That log should have ALL necessary info for off-chain actors Everyone should be able to ENTIRELY rely on log messages */ // `TBTCDepositToken` mints a token for every new Deposit. // If a token exists for a given ID, we know it is a valid Deposit address. TBTCDepositToken tbtcDepositToken; // This event is fired when we init the deposit event Created( address indexed _depositContractAddress, address indexed _keepAddress, uint256 _timestamp ); // This log event contains all info needed to rebuild the redemption tx // We index on request and signers and digest event RedemptionRequested( address indexed _depositContractAddress, address indexed _requester, bytes32 indexed _digest, uint256 _utxoValue, bytes _redeemerOutputScript, uint256 _requestedFee, bytes _outpoint ); // This log event contains all info needed to build a witnes // We index the digest so that we can search events for the other log event GotRedemptionSignature( address indexed _depositContractAddress, bytes32 indexed _digest, bytes32 _r, bytes32 _s, uint256 _timestamp ); // This log is fired when the signing group returns a public key event RegisteredPubkey( address indexed _depositContractAddress, bytes32 _signingGroupPubkeyX, bytes32 _signingGroupPubkeyY, uint256 _timestamp ); // This event is fired when we enter the FAILED_SETUP state for any reason event SetupFailed( address indexed _depositContractAddress, uint256 _timestamp ); // This event is fired when a funder requests funder abort after // FAILED_SETUP has been reached. Funder abort is a voluntary signer action // to return UTXO(s) that were sent to a signer-controlled wallet despite // the funding proofs having failed. event FunderAbortRequested( address indexed _depositContractAddress, bytes _abortOutputScript ); // This event is fired when we detect an ECDSA fraud before seeing a funding proof event FraudDuringSetup( address indexed _depositContractAddress, uint256 _timestamp ); // This event is fired when we enter the ACTIVE state event Funded( address indexed _depositContractAddress, bytes32 indexed _txid, uint256 _timestamp ); // This event is called when we enter the COURTESY_CALL state event CourtesyCalled( address indexed _depositContractAddress, uint256 _timestamp ); // This event is fired when we go from COURTESY_CALL to ACTIVE event ExitedCourtesyCall( address indexed _depositContractAddress, uint256 _timestamp ); // This log event is fired when liquidation event StartedLiquidation( address indexed _depositContractAddress, bool _wasFraud, uint256 _timestamp ); // This event is fired when the Redemption SPV proof is validated event Redeemed( address indexed _depositContractAddress, bytes32 indexed _txid, uint256 _timestamp ); // This event is fired when Liquidation is completed event Liquidated( address indexed _depositContractAddress, uint256 _timestamp ); // // Logging // /// @notice Fires a Created event. /// @dev We append the sender, which is the deposit contract that called. /// @param _keepAddress The address of the associated keep. /// @return True if successful, else revert. function logCreated(address _keepAddress) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Created(msg.sender, _keepAddress, block.timestamp); } /// @notice Fires a RedemptionRequested event. /// @dev This is the only event without an explicit timestamp. /// @param _requester The ethereum address of the requester. /// @param _digest The calculated sighash digest. /// @param _utxoValue The size of the utxo in sat. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _requestedFee The requester or bump-system specified fee. /// @param _outpoint The 36 byte outpoint. /// @return True if successful, else revert. function logRedemptionRequested( address _requester, bytes32 _digest, uint256 _utxoValue, bytes memory _redeemerOutputScript, uint256 _requestedFee, bytes memory _outpoint ) public { // not external to allow bytes memory parameters require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit RedemptionRequested( msg.sender, _requester, _digest, _utxoValue, _redeemerOutputScript, _requestedFee, _outpoint ); } /// @notice Fires a GotRedemptionSignature event. /// @dev We append the sender, which is the deposit contract that called. /// @param _digest signed digest. /// @param _r signature r value. /// @param _s signature s value. function logGotRedemptionSignature(bytes32 _digest, bytes32 _r, bytes32 _s) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit GotRedemptionSignature( msg.sender, _digest, _r, _s, block.timestamp ); } /// @notice Fires a RegisteredPubkey event. /// @dev We append the sender, which is the deposit contract that called. function logRegisteredPubkey( bytes32 _signingGroupPubkeyX, bytes32 _signingGroupPubkeyY ) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit RegisteredPubkey( msg.sender, _signingGroupPubkeyX, _signingGroupPubkeyY, block.timestamp ); } /// @notice Fires a SetupFailed event. /// @dev We append the sender, which is the deposit contract that called. function logSetupFailed() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit SetupFailed(msg.sender, block.timestamp); } /// @notice Fires a FunderAbortRequested event. /// @dev We append the sender, which is the deposit contract that called. function logFunderRequestedAbort(bytes memory _abortOutputScript) public { // not external to allow bytes memory parameters require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit FunderAbortRequested(msg.sender, _abortOutputScript); } /// @notice Fires a FraudDuringSetup event. /// @dev We append the sender, which is the deposit contract that called. function logFraudDuringSetup() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit FraudDuringSetup(msg.sender, block.timestamp); } /// @notice Fires a Funded event. /// @dev We append the sender, which is the deposit contract that called. function logFunded(bytes32 _txid) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Funded(msg.sender, _txid, block.timestamp); } /// @notice Fires a CourtesyCalled event. /// @dev We append the sender, which is the deposit contract that called. function logCourtesyCalled() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit CourtesyCalled(msg.sender, block.timestamp); } /// @notice Fires a StartedLiquidation event. /// @dev We append the sender, which is the deposit contract that called. /// @param _wasFraud True if liquidating for fraud. function logStartedLiquidation(bool _wasFraud) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit StartedLiquidation(msg.sender, _wasFraud, block.timestamp); } /// @notice Fires a Redeemed event /// @dev We append the sender, which is the deposit contract that called. function logRedeemed(bytes32 _txid) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Redeemed(msg.sender, _txid, block.timestamp); } /// @notice Fires a Liquidated event /// @dev We append the sender, which is the deposit contract that called. function logLiquidated() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Liquidated(msg.sender, block.timestamp); } /// @notice Fires a ExitedCourtesyCall event /// @dev We append the sender, which is the deposit contract that called. function logExitedCourtesyCall() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit ExitedCourtesyCall(msg.sender, block.timestamp); } /// @notice Sets the tbtcDepositToken contract. /// @dev The contract is used by `approvedToLog` to check if the /// caller is a Deposit contract. This should only be called once. /// @param _tbtcDepositTokenAddress The address of the tbtcDepositToken. function setTbtcDepositToken(TBTCDepositToken _tbtcDepositTokenAddress) internal { require( address(tbtcDepositToken) == address(0), "tbtcDepositToken is already set" ); tbtcDepositToken = _tbtcDepositTokenAddress; } // // AUTH // /// @notice Checks if an address is an allowed logger. /// @dev checks tbtcDepositToken to see if the caller represents /// an existing deposit. /// We don't require this, so deposits are not bricked if the system borks. /// @param _caller The address of the calling contract. /// @return True if approved, otherwise false. function approvedToLog(address _caller) public view returns (bool) { return tbtcDepositToken.exists(uint256(_caller)); } } pragma solidity 0.5.17; import {ERC721Metadata} from "openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol"; import {DepositFactoryAuthority} from "./DepositFactoryAuthority.sol"; import {ITokenRecipient} from "../interfaces/ITokenRecipient.sol"; /// @title tBTC Deposit Token for tracking deposit ownership /// @notice The tBTC Deposit Token, commonly referenced as the TDT, is an /// ERC721 non-fungible token whose ownership reflects the ownership /// of its corresponding deposit. Each deposit has one TDT, and vice /// versa. Owning a TDT is equivalent to owning its corresponding /// deposit. TDTs can be transferred freely. tBTC's VendingMachine /// contract takes ownership of TDTs and in exchange returns fungible /// TBTC tokens whose value is backed 1-to-1 by the corresponding /// deposit's BTC. /// @dev Currently, TDTs are minted using the uint256 casting of the /// corresponding deposit contract's address. That is, the TDT's id is /// convertible to the deposit's address and vice versa. TDTs are minted /// automatically by the factory during each deposit's initialization. See /// DepositFactory.createNewDeposit() for more info on how the TDT is minted. contract TBTCDepositToken is ERC721Metadata, DepositFactoryAuthority { constructor(address _depositFactoryAddress) ERC721Metadata("tBTC Deposit Token", "TDT") public { initialize(_depositFactoryAddress); } /// @dev Mints a new token. /// Reverts if the given token ID already exists. /// @param _to The address that will own the minted token /// @param _tokenId uint256 ID of the token to be minted function mint(address _to, uint256 _tokenId) external onlyFactory { _mint(_to, _tokenId); } /// @dev Returns whether the specified token exists. /// @param _tokenId uint256 ID of the token to query the existence of. /// @return bool whether the token exists. function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } /// @notice Allow another address to spend on the caller's behalf. /// Set allowance for other address and notify. /// Allows `_spender` to transfer the specified TDT /// on your behalf and then ping the contract about it. /// @dev The `_spender` should implement the `ITokenRecipient` /// interface below to receive approval notifications. /// @param _spender `ITokenRecipient`-conforming contract authorized to /// operate on the approved token. /// @param _tdtId The TDT they can spend. /// @param _extraData Extra information to send to the approved contract. function approveAndCall( ITokenRecipient _spender, uint256 _tdtId, bytes memory _extraData ) public returns (bool) { // not external to allow bytes memory parameters approve(address(_spender), _tdtId); _spender.receiveApproval(msg.sender, _tdtId, address(this), _extraData); return true; } } /* Authored by Satoshi Nakamoto 🤪 */ pragma solidity 0.5.17; import {ERC20} from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import {ERC20Detailed} from "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; import {VendingMachineAuthority} from "./VendingMachineAuthority.sol"; import {ITokenRecipient} from "../interfaces/ITokenRecipient.sol"; /// @title TBTC Token. /// @notice This is the TBTC ERC20 contract. /// @dev Tokens can only be minted by the `VendingMachine` contract. contract TBTCToken is ERC20Detailed, ERC20, VendingMachineAuthority { /// @dev Constructor, calls ERC20Detailed constructor to set Token info /// ERC20Detailed(TokenName, TokenSymbol, NumberOfDecimals) constructor(address _VendingMachine) ERC20Detailed("tBTC", "TBTC", 18) VendingMachineAuthority(_VendingMachine) public { // solium-disable-previous-line no-empty-blocks } /// @dev Mints an amount of the token and assigns it to an account. /// Uses the internal _mint function. /// @param _account The account that will receive the created tokens. /// @param _amount The amount of tokens that will be created. function mint(address _account, uint256 _amount) public onlyVendingMachine returns (bool) { // NOTE: this is a public function with unchecked minting. _mint(_account, _amount); return true; } /// @dev Burns an amount of the token from the given account's balance. /// deducting from the sender's allowance for said account. /// Uses the internal _burn function. /// @param _account The account whose tokens will be burnt. /// @param _amount The amount of tokens that will be burnt. function burnFrom(address _account, uint256 _amount) public { _burnFrom(_account, _amount); } /// @dev Destroys `amount` tokens from `msg.sender`, reducing the /// total supply. /// @param _amount The amount of tokens that will be burnt. function burn(uint256 _amount) public { _burn(msg.sender, _amount); } /// @notice 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. /// @dev The `_spender` should implement the `ITokenRecipient` /// interface to receive approval notifications. /// @param _spender Address of contract authorized to spend. /// @param _value The max amount they can spend. /// @param _extraData Extra information to send to the approved contract. /// @return true if the `_spender` was successfully approved and acted on /// the approval, false (or revert) otherwise. function approveAndCall(ITokenRecipient _spender, uint256 _value, bytes memory _extraData) public returns (bool) { if (approve(address(_spender), _value)) { _spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } return false; } } pragma solidity 0.5.17; /// @title Deposit Factory Authority /// @notice Contract to secure function calls to the Deposit Factory. /// @dev Secured by setting the depositFactory address and using the onlyFactory /// modifier on functions requiring restriction. contract DepositFactoryAuthority { bool internal _initialized = false; address internal _depositFactory; /// @notice Set the address of the System contract on contract /// initialization. /// @dev Since this function is not access-controlled, it should be called /// transactionally with contract instantiation. In cases where a /// regular contract directly inherits from DepositFactoryAuthority, /// that should happen in the constructor. In cases where the inheritor /// is binstead used via a clone factory, the same function that /// creates a new clone should also trigger initialization. function initialize(address _factory) public { require(_factory != address(0), "Factory cannot be the zero address."); require(! _initialized, "Factory can only be initialized once."); _depositFactory = _factory; _initialized = true; } /// @notice Function modifier ensures modified function is only called by set deposit factory. modifier onlyFactory(){ require(_initialized, "Factory initialization must have been called."); require(msg.sender == _depositFactory, "Caller must be depositFactory contract"); _; } } pragma solidity 0.5.17; /// @title TBTC System Authority. /// @notice Contract to secure function calls to the TBTC System contract. /// @dev The `TBTCSystem` contract address is passed as a constructor parameter. contract TBTCSystemAuthority { address internal tbtcSystemAddress; /// @notice Set the address of the System contract on contract initialization. constructor(address _tbtcSystemAddress) public { tbtcSystemAddress = _tbtcSystemAddress; } /// @notice Function modifier ensures modified function is only called by TBTCSystem. modifier onlyTbtcSystem(){ require(msg.sender == tbtcSystemAddress, "Caller must be tbtcSystem contract"); _; } } pragma solidity 0.5.17; /// @title Vending Machine Authority. /// @notice Contract to secure function calls to the Vending Machine. /// @dev Secured by setting the VendingMachine address and using the /// onlyVendingMachine modifier on functions requiring restriction. contract VendingMachineAuthority { address internal VendingMachine; constructor(address _vendingMachine) public { VendingMachine = _vendingMachine; } /// @notice Function modifier ensures modified function caller address is the vending machine. modifier onlyVendingMachine() { require(msg.sender == VendingMachine, "caller must be the vending machine"); _; } } pragma solidity 0.5.17; /// @title Interface of recipient contract for `approveAndCall` pattern. /// Implementors will be able to be used in an `approveAndCall` /// interaction with a supporting contract, such that a token approval /// can call the contract acting on that approval in a single /// transaction. /// /// See the `FundingScript` and `RedemptionScript` contracts as examples. interface ITokenRecipient { /// Typically called from a token contract's `approveAndCall` method, this /// method will receive the original owner of the token (`_from`), the /// transferred `_value` (in the case of an ERC721, the token id), the token /// address (`_token`), and a blob of `_extraData` that is informally /// specified by the implementor of this method as a way to communicate /// additional parameters. /// /// Token calls to `receiveApproval` should revert if `receiveApproval` /// reverts, and reverts should remove the approval. /// /// @param _from The original owner of the token approved for transfer. /// @param _value For an ERC20, the amount approved for transfer; for an /// ERC721, the id of the token approved for transfer. /// @param _token The address of the contract for the token whose transfer /// was approved. /// @param _extraData An additional data blob forwarded unmodified through /// `approveAndCall`, used to allow the token owner to pass /// additional parameters and data to this method. The structure of /// the extra data is informally specified by the implementor of /// this interface. function receiveApproval( address _from, uint256 _value, address _token, bytes calldata _extraData ) external; } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol"; import "./VendingMachineAuthority.sol"; /// @title Fee Rebate Token /// @notice The Fee Rebate Token (FRT) is a non fungible token (ERC721) /// the ID of which corresponds to a given deposit address. /// If the corresponding deposit is still active, ownership of this token /// could result in reimbursement of the signer fee paid to open the deposit. /// @dev This token is minted automatically when a TDT (`TBTCDepositToken`) /// is exchanged for TBTC (`TBTCToken`) via the Vending Machine (`VendingMachine`). /// When the Deposit is redeemed, the TDT holder will be reimbursed /// the signer fee if the redeemer is not the TDT holder and Deposit is not /// at-term or in COURTESY_CALL. contract FeeRebateToken is ERC721Metadata, VendingMachineAuthority { constructor(address _vendingMachine) ERC721Metadata("tBTC Fee Rebate Token", "FRT") VendingMachineAuthority(_vendingMachine) public { // solium-disable-previous-line no-empty-blocks } /// @dev Mints a new token. /// Reverts if the given token ID already exists. /// @param _to The address that will own the minted token. /// @param _tokenId uint256 ID of the token to be minted. function mint(address _to, uint256 _tokenId) external onlyVendingMachine { _mint(_to, _tokenId); } /// @dev Returns whether the specified token exists. /// @param _tokenId uint256 ID of the token to query the existence of. /// @return bool whether the token exists. function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } } /** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; /// @title ECDSA Keep /// @notice Contract reflecting an ECDSA keep. contract IBondedECDSAKeep { /// @notice Returns public key of this keep. /// @return Keeps's public key. function getPublicKey() external view returns (bytes memory); /// @notice Returns the amount of the keep's ETH bond in wei. /// @return The amount of the keep's ETH bond in wei. function checkBondAmount() external view returns (uint256); /// @notice Calculates a signature over provided digest by the keep. Note that /// signatures from the keep not explicitly requested by calling `sign` /// will be provable as fraud via `submitSignatureFraud`. /// @param _digest Digest to be signed. function sign(bytes32 _digest) external; /// @notice Distributes ETH reward evenly across keep signer beneficiaries. /// @dev Only the value passed to this function is distributed. function distributeETHReward() external payable; /// @notice Distributes ERC20 reward evenly across keep signer beneficiaries. /// @dev This works with any ERC20 token that implements a transferFrom /// function. /// This function only has authority over pre-approved /// token amount. We don't explicitly check for allowance, SafeMath /// subtraction overflow is enough protection. /// @param _tokenAddress Address of the ERC20 token to distribute. /// @param _value Amount of ERC20 token to distribute. function distributeERC20Reward(address _tokenAddress, uint256 _value) external; /// @notice Seizes the signers' ETH bonds. After seizing bonds keep is /// terminated so it will no longer respond to signing requests. Bonds can /// be seized only when there is no signing in progress or requested signing /// process has timed out. This function seizes all of signers' bonds. /// The application may decide to return part of bonds later after they are /// processed using returnPartialSignerBonds function. function seizeSignerBonds() external; /// @notice Returns partial signer's ETH bonds to the pool as an unbounded /// value. This function is called after bonds have been seized and processed /// by the privileged application after calling seizeSignerBonds function. /// It is entirely up to the application if a part of signers' bonds is /// returned. The application may decide for that but may also decide to /// seize bonds and do not return anything. function returnPartialSignerBonds() external payable; /// @notice Submits a fraud proof for a valid signature from this keep that was /// not first approved via a call to sign. /// @dev The function expects the signed digest to be calculated as a sha256 /// hash of the preimage: `sha256(_preimage)`. /// @param _v Signature's header byte: `27 + recoveryID`. /// @param _r R part of ECDSA signature. /// @param _s S part of ECDSA signature. /// @param _signedDigest Digest for the provided signature. Result of hashing /// the preimage. /// @param _preimage Preimage of the hashed message. /// @return True if fraud, error otherwise. function submitSignatureFraud( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes calldata _preimage ) external returns (bool _isFraud); /// @notice Closes keep when no longer needed. Releases bonds to the keep /// members. Keep can be closed only when there is no signing in progress or /// requested signing process has timed out. /// @dev The function can be called only by the owner of the keep and only /// if the keep has not been already closed. function closeKeep() external; } pragma solidity ^0.5.10; /** @title ValidateSPV*/ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {SafeMath} from "./SafeMath.sol"; import {BTCUtils} from "./BTCUtils.sol"; library ValidateSPV { using BTCUtils for bytes; using BTCUtils for uint256; using BytesLib for bytes; using SafeMath for uint256; enum InputTypes { NONE, LEGACY, COMPATIBILITY, WITNESS } enum OutputTypes { NONE, WPKH, WSH, OP_RETURN, PKH, SH, NONSTANDARD } uint256 constant ERR_BAD_LENGTH = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant ERR_INVALID_CHAIN = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe; uint256 constant ERR_LOW_WORK = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd; function getErrBadLength() internal pure returns (uint256) { return ERR_BAD_LENGTH; } function getErrInvalidChain() internal pure returns (uint256) { return ERR_INVALID_CHAIN; } function getErrLowWork() internal pure returns (uint256) { return ERR_LOW_WORK; } /// @notice Validates a tx inclusion in the block /// @dev `index` is not a reliable indicator of location within a block /// @param _txid The txid (LE) /// @param _merkleRoot The merkle root (as in the block header) /// @param _intermediateNodes The proof's intermediate nodes (digests between leaf and root) /// @param _index The leaf's index in the tree (0-indexed) /// @return true if fully valid, false otherwise function prove( bytes32 _txid, bytes32 _merkleRoot, bytes memory _intermediateNodes, uint _index ) internal pure returns (bool) { // Shortcut the empty-block case if (_txid == _merkleRoot && _index == 0 && _intermediateNodes.length == 0) { return true; } bytes memory _proof = abi.encodePacked(_txid, _intermediateNodes, _merkleRoot); // If the Merkle proof failed, bubble up error return _proof.verifyHash256Merkle(_index); } /// @notice Hashes transaction to get txid /// @dev Supports Legacy and Witness /// @param _version 4-bytes version /// @param _vin Raw bytes length-prefixed input vector /// @param _vout Raw bytes length-prefixed output vector /// @param _locktime 4-byte tx locktime /// @return 32-byte transaction id, little endian function calculateTxId( bytes memory _version, bytes memory _vin, bytes memory _vout, bytes memory _locktime ) internal pure returns (bytes32) { // Get transaction hash double-Sha256(version + nIns + inputs + nOuts + outputs + locktime) return abi.encodePacked(_version, _vin, _vout, _locktime).hash256(); } /// @notice Checks validity of header chain /// @notice Compares the hash of each header to the prevHash in the next header /// @param _headers Raw byte array of header chain /// @return The total accumulated difficulty of the header chain, or an error code function validateHeaderChain(bytes memory _headers) internal view returns (uint256 _totalDifficulty) { // Check header chain length if (_headers.length % 80 != 0) {return ERR_BAD_LENGTH;} // Initialize header start index bytes32 _digest; _totalDifficulty = 0; for (uint256 _start = 0; _start < _headers.length; _start += 80) { // ith header start index and ith header bytes memory _header = _headers.slice(_start, 80); // After the first header, check that headers are in a chain if (_start != 0) { if (!validateHeaderPrevHash(_header, _digest)) {return ERR_INVALID_CHAIN;} } // ith header target uint256 _target = _header.extractTarget(); // Require that the header has sufficient work _digest = _header.hash256View(); if(uint256(_digest).reverseUint256() > _target) { return ERR_LOW_WORK; } // Add ith header difficulty to difficulty sum _totalDifficulty = _totalDifficulty.add(_target.calculateDifficulty()); } } /// @notice Checks validity of header work /// @param _digest Header digest /// @param _target The target threshold /// @return true if header work is valid, false otherwise function validateHeaderWork(bytes32 _digest, uint256 _target) internal pure returns (bool) { if (_digest == bytes32(0)) {return false;} return (abi.encodePacked(_digest).reverseEndianness().bytesToUint() < _target); } /// @notice Checks validity of header chain /// @dev Compares current header prevHash to previous header's digest /// @param _header The raw bytes header /// @param _prevHeaderDigest The previous header's digest /// @return true if the connect is valid, false otherwise function validateHeaderPrevHash(bytes memory _header, bytes32 _prevHeaderDigest) internal pure returns (bool) { // Extract prevHash of current header bytes32 _prevHash = _header.extractPrevBlockLE().toBytes32(); // Compare prevHash of current header to previous header's digest if (_prevHash != _prevHeaderDigest) {return false;} return true; } } pragma solidity ^0.5.10; /** @title CheckBitcoinSigs */ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {BTCUtils} from "./BTCUtils.sol"; library CheckBitcoinSigs { using BytesLib for bytes; using BTCUtils for bytes; /// @notice Derives an Ethereum Account address from a pubkey /// @dev The address is the last 20 bytes of the keccak256 of the address /// @param _pubkey The public key X & Y. Unprefixed, as a 64-byte array /// @return The account address function accountFromPubkey(bytes memory _pubkey) internal pure returns (address) { require(_pubkey.length == 64, "Pubkey must be 64-byte raw, uncompressed key."); // keccak hash of uncompressed unprefixed pubkey bytes32 _digest = keccak256(_pubkey); return address(uint256(_digest)); } /// @notice Calculates the p2wpkh output script of a pubkey /// @dev Compresses keys to 33 bytes as required by Bitcoin /// @param _pubkey The public key, compressed or uncompressed /// @return The p2wkph output script function p2wpkhFromPubkey(bytes memory _pubkey) internal pure returns (bytes memory) { bytes memory _compressedPubkey; uint8 _prefix; if (_pubkey.length == 64) { _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2; _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice(0, 32)); } else if (_pubkey.length == 65) { _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2; _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice(1, 32)); } else { _compressedPubkey = _pubkey; } require(_compressedPubkey.length == 33, "Witness PKH requires compressed keys"); bytes memory _pubkeyHash = _compressedPubkey.hash160(); return abi.encodePacked(hex"0014", _pubkeyHash); } /// @notice checks a signed message's validity under a pubkey /// @dev does this using ecrecover because Ethereum has no soul /// @param _pubkey the public key to check (64 bytes) /// @param _digest the message digest signed /// @param _v the signature recovery value /// @param _r the signature r value /// @param _s the signature s value /// @return true if signature is valid, else false function checkSig( bytes memory _pubkey, bytes32 _digest, uint8 _v, bytes32 _r, bytes32 _s ) internal pure returns (bool) { require(_pubkey.length == 64, "Requires uncompressed unprefixed pubkey"); address _expected = accountFromPubkey(_pubkey); address _actual = ecrecover(_digest, _v, _r, _s); return _actual == _expected; } /// @notice checks a signed message against a bitcoin p2wpkh output script /// @dev does this my verifying the p2wpkh matches an ethereum account /// @param _p2wpkhOutputScript the bitcoin output script /// @param _pubkey the uncompressed, unprefixed public key to check /// @param _digest the message digest signed /// @param _v the signature recovery value /// @param _r the signature r value /// @param _s the signature s value /// @return true if signature is valid, else false function checkBitcoinSig( bytes memory _p2wpkhOutputScript, bytes memory _pubkey, bytes32 _digest, uint8 _v, bytes32 _r, bytes32 _s ) internal pure returns (bool) { require(_pubkey.length == 64, "Requires uncompressed unprefixed pubkey"); bool _isExpectedSigner = keccak256(p2wpkhFromPubkey(_pubkey)) == keccak256(_p2wpkhOutputScript); // is it the expected signer? if (!_isExpectedSigner) {return false;} bool _sigResult = checkSig(_pubkey, _digest, _v, _r, _s); return _sigResult; } /// @notice checks if a message is the sha256 preimage of a digest /// @dev this is NOT the hash256! this step is necessary for ECDSA security! /// @param _digest the digest /// @param _candidate the purported preimage /// @return true if the preimage matches the digest, else false function isSha256Preimage( bytes memory _candidate, bytes32 _digest ) internal pure returns (bool) { return sha256(_candidate) == _digest; } /// @notice checks if a message is the keccak256 preimage of a digest /// @dev this step is necessary for ECDSA security! /// @param _digest the digest /// @param _candidate the purported preimage /// @return true if the preimage matches the digest, else false function isKeccak256Preimage( bytes memory _candidate, bytes32 _digest ) internal pure returns (bool) { return keccak256(_candidate) == _digest; } /// @notice calculates the signature hash of a Bitcoin transaction with the provided details /// @dev documented in bip143. many values are hardcoded here /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey)) /// @param _inputValue the value of the input in satoshi /// @param _outputValue the value of the output in satoshi /// @param _outputScript the length-prefixed output script /// @return the double-sha256 (hash256) signature hash as defined by bip143 function wpkhSpendSighash( bytes memory _outpoint, // 36-byte UTXO id bytes20 _inputPKH, // 20-byte hash160 bytes8 _inputValue, // 8-byte LE bytes8 _outputValue, // 8-byte LE bytes memory _outputScript // lenght-prefixed output script ) internal pure returns (bytes32) { // Fixes elements to easily make a 1-in 1-out sighash digest // Does not support timelocks bytes memory _scriptCode = abi.encodePacked( hex"1976a914", // length, dup, hash160, pkh_length _inputPKH, hex"88ac"); // equal, checksig bytes32 _hashOutputs = abi.encodePacked( _outputValue, // 8-byte LE _outputScript).hash256(); bytes memory _sighashPreimage = abi.encodePacked( hex"01000000", // version _outpoint.hash256(), // hashPrevouts hex"8cb9012517c817fead650287d61bdd9c68803b6bf9c64133dcab3e65b5a50cb9", // hashSequence(00000000) _outpoint, // outpoint _scriptCode, // p2wpkh script code _inputValue, // value of the input in 8-byte LE hex"00000000", // input nSequence _hashOutputs, // hash of the single output hex"00000000", // nLockTime hex"01000000" // SIGHASH_ALL ); return _sighashPreimage.hash256(); } /// @notice calculates the signature hash of a Bitcoin transaction with the provided details /// @dev documented in bip143. many values are hardcoded here /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey)) /// @param _inputValue the value of the input in satoshi /// @param _outputValue the value of the output in satoshi /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey)) /// @return the double-sha256 (hash256) signature hash as defined by bip143 function wpkhToWpkhSighash( bytes memory _outpoint, // 36-byte UTXO id bytes20 _inputPKH, // 20-byte hash160 bytes8 _inputValue, // 8-byte LE bytes8 _outputValue, // 8-byte LE bytes20 _outputPKH // 20-byte hash160 ) internal pure returns (bytes32) { return wpkhSpendSighash( _outpoint, _inputPKH, _inputValue, _outputValue, abi.encodePacked( hex"160014", // wpkh tag _outputPKH) ); } /// @notice Preserved for API compatibility with older version /// @dev documented in bip143. many values are hardcoded here /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey)) /// @param _inputValue the value of the input in satoshi /// @param _outputValue the value of the output in satoshi /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey)) /// @return the double-sha256 (hash256) signature hash as defined by bip143 function oneInputOneOutputSighash( bytes memory _outpoint, // 36-byte UTXO id bytes20 _inputPKH, // 20-byte hash160 bytes8 _inputValue, // 8-byte LE bytes8 _outputValue, // 8-byte LE bytes20 _outputPKH // 20-byte hash160 ) internal pure returns (bytes32) { return wpkhToWpkhSighash(_outpoint, _inputPKH, _inputValue, _outputValue, _outputPKH); } } pragma solidity ^0.5.0; 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`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => 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(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @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. * * > Note that 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; } } pragma solidity ^0.5.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either `approve` or `setApproveForAll`. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either `approve` or `setApproveForAll`. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } pragma solidity ^0.5.0; import "./ERC721.sol"; import "./IERC721Metadata.sol"; import "../../introspection/ERC165.sol"; contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } pragma solidity ^0.5.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../drafts/Counters.sol"; import "../../introspection/ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use `safeTransferFrom` whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `onERC721Received` on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } pragma solidity ^0.5.0; import "../math/SafeMath.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 Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC165 standard, as defined in the * [EIP](https://eips.ethereum.org/EIPS/eip-165). * * 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 * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * 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); } pragma solidity ^0.5.0; import "./IERC165.sol"; /** * @dev Implementation of the `IERC165` interface. * * Contracts may inherit from this and call `_registerInterface` to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // 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) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See `IERC165.supportsInterface`. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } pragma solidity ^0.5.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); }
Extracts the target from a block header Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent _header The header return The target threshold
function extractTarget(bytes memory _header) internal pure returns (uint256) { bytes memory _m = _header.slice(72, 3); uint8 _e = uint8(_header[75]); uint256 _mantissa = bytesToUint(reverseEndianness(_m)); uint _exponent = _e - 3; return _mantissa * (256 ** _exponent); }
7,283,279
/* Copyright 2018 RigoBlock, Rigo Investment Sagl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.0; import { Owned } from "../../../utils/Owned/Owned.sol"; import { ExchangesAuthorityFace } from "./ExchangesAuthorityFace.sol"; /// @title Exchanges Authority - A helper contract for the exchange adapters. /// @author Gabriele Rigo - <[email protected]> // solhint-disable-next-line contract ExchangesAuthority is Owned, ExchangesAuthorityFace { BuildingBlocks public blocks; Type public types; mapping (address => Account) public accounts; struct List { address target; } struct Type { string types; List[] list; } struct Group { bool whitelister; bool exchange; bool asset; bool authority; bool wrapper; bool proxy; } struct Account { address account; bool authorized; mapping (bool => Group) groups; //mapping account to bool authorized to bool group } struct BuildingBlocks { address exchangeEventful; address sigVerifier; address casper; mapping (address => bool) initialized; mapping (address => address) adapter; // Mapping of exchange => method => approved mapping (address => mapping (bytes4 => bool)) allowedMethods; mapping (address => mapping (address => bool)) allowedTokens; mapping (address => mapping (address => bool)) allowedWrappers; } /* * EVENTS */ event AuthoritySet(address indexed authority); event WhitelisterSet(address indexed whitelister); event WhitelistedAsset(address indexed asset, bool approved); event WhitelistedExchange(address indexed exchange, bool approved); event WhitelistedWrapper(address indexed wrapper, bool approved); event WhitelistedProxy(address indexed proxy, bool approved); event WhitelistedMethod(bytes4 indexed method, address indexed adapter, bool approved); event NewSigVerifier(address indexed sigVerifier); event NewExchangeEventful(address indexed exchangeEventful); event NewCasper(address indexed casper); /* * MODIFIERS */ modifier onlyAdmin { require(msg.sender == owner || isWhitelister(msg.sender)); _; } modifier onlyWhitelister { require(isWhitelister(msg.sender)); _; } /* * CORE FUNCTIONS */ /// @dev Allows the owner to whitelist an authority /// @param _authority Address of the authority /// @param _isWhitelisted Bool whitelisted function setAuthority(address _authority, bool _isWhitelisted) external onlyOwner { setAuthorityInternal(_authority, _isWhitelisted); } /// @dev Allows the owner to whitelist a whitelister /// @param _whitelister Address of the whitelister /// @param _isWhitelisted Bool whitelisted function setWhitelister(address _whitelister, bool _isWhitelisted) external onlyOwner { setWhitelisterInternal(_whitelister, _isWhitelisted); } /// @dev Allows a whitelister to whitelist an asset /// @param _asset Address of the token /// @param _isWhitelisted Bool whitelisted function whitelistAsset(address _asset, bool _isWhitelisted) external onlyWhitelister { accounts[_asset].account = _asset; accounts[_asset].authorized = _isWhitelisted; accounts[_asset].groups[_isWhitelisted].asset = _isWhitelisted; types.list.push(List(_asset)); emit WhitelistedAsset(_asset, _isWhitelisted); } /// @dev Allows a whitelister to whitelist an exchange /// @param _exchange Address of the target exchange /// @param _isWhitelisted Bool whitelisted function whitelistExchange(address _exchange, bool _isWhitelisted) external onlyWhitelister { accounts[_exchange].account = _exchange; accounts[_exchange].authorized = _isWhitelisted; accounts[_exchange].groups[_isWhitelisted].exchange = _isWhitelisted; types.list.push(List(_exchange)); emit WhitelistedExchange(_exchange, _isWhitelisted); } /// @dev Allows a whitelister to whitelist an token wrapper /// @param _wrapper Address of the target token wrapper /// @param _isWhitelisted Bool whitelisted function whitelistWrapper(address _wrapper, bool _isWhitelisted) external onlyWhitelister { accounts[_wrapper].account = _wrapper; accounts[_wrapper].authorized = _isWhitelisted; accounts[_wrapper].groups[_isWhitelisted].wrapper = _isWhitelisted; types.list.push(List(_wrapper)); emit WhitelistedWrapper(_wrapper, _isWhitelisted); } /// @dev Allows a whitelister to whitelist a tokenTransferProxy /// @param _tokenTransferProxy Address of the proxy /// @param _isWhitelisted Bool whitelisted function whitelistTokenTransferProxy( address _tokenTransferProxy, bool _isWhitelisted) external onlyWhitelister { accounts[_tokenTransferProxy].account = _tokenTransferProxy; accounts[_tokenTransferProxy].authorized = _isWhitelisted; accounts[_tokenTransferProxy].groups[_isWhitelisted].proxy = _isWhitelisted; types.list.push(List(_tokenTransferProxy)); emit WhitelistedProxy(_tokenTransferProxy, _isWhitelisted); } /// @dev Allows a whitelister to enable trading on a particular exchange /// @param _asset Address of the token /// @param _exchange Address of the exchange /// @param _isWhitelisted Bool whitelisted function whitelistAssetOnExchange( address _asset, address _exchange, bool _isWhitelisted) external onlyAdmin { blocks.allowedTokens[_exchange][_asset] = _isWhitelisted; emit WhitelistedAsset(_asset, _isWhitelisted); } /// @dev Allows a whitelister to enable assiciate wrappers to a token /// @param _token Address of the token /// @param _wrapper Address of the exchange /// @param _isWhitelisted Bool whitelisted function whitelistTokenOnWrapper(address _token, address _wrapper, bool _isWhitelisted) external onlyAdmin { blocks.allowedWrappers[_wrapper][_token] = _isWhitelisted; emit WhitelistedAsset(_token, _isWhitelisted); } /// @dev Allows an admin to whitelist a factory /// @param _method Hex of the function ABI /// @param _isWhitelisted Bool whitelisted function whitelistMethod( bytes4 _method, address _adapter, bool _isWhitelisted) external onlyAdmin { blocks.allowedMethods[_adapter][_method] = _isWhitelisted; emit WhitelistedMethod(_method, _adapter, _isWhitelisted); } /// @dev Allows the owner to set the signature verifier /// @param _sigVerifier Address of the verifier contract function setSignatureVerifier(address _sigVerifier) external onlyOwner { blocks.sigVerifier = _sigVerifier; emit NewSigVerifier(blocks.sigVerifier); } /// @dev Allows the owner to set the exchange eventful /// @param _exchangeEventful Address of the exchange logs contract function setExchangeEventful(address _exchangeEventful) external onlyOwner { blocks.exchangeEventful = _exchangeEventful; emit NewExchangeEventful(blocks.exchangeEventful); } /// @dev Allows the owner to associate an exchange to its adapter /// @param _exchange Address of the exchange /// @param _adapter Address of the adapter function setExchangeAdapter(address _exchange, address _adapter) external onlyOwner { require(_exchange != _adapter); blocks.adapter[_exchange] = _adapter; } /// @dev Allows the owner to set the casper contract /// @param _casper Address of the casper contract function setCasper(address _casper) external onlyOwner { blocks.casper = _casper; blocks.initialized[_casper] = true; emit NewCasper(blocks.casper); } /* * CONSTANT PUBLIC FUNCTIONS */ /// @dev Provides whether an address is an authority /// @param _authority Address of the target authority /// @return Bool is whitelisted function isAuthority(address _authority) external view returns (bool) { return accounts[_authority].groups[true].authority; } /// @dev Provides whether an asset is whitelisted /// @param _asset Address of the target asset /// @return Bool is whitelisted function isWhitelistedAsset(address _asset) external view returns (bool) { return accounts[_asset].groups[true].asset; } /// @dev Provides whether an exchange is whitelisted /// @param _exchange Address of the target exchange /// @return Bool is whitelisted function isWhitelistedExchange(address _exchange) external view returns (bool) { return accounts[_exchange].groups[true].exchange; } /// @dev Provides whether a token wrapper is whitelisted /// @param _wrapper Address of the target exchange /// @return Bool is whitelisted function isWhitelistedWrapper(address _wrapper) external view returns (bool) { return accounts[_wrapper].groups[true].wrapper; } /// @dev Provides whether a proxy is whitelisted /// @param _tokenTransferProxy Address of the proxy /// @return Bool is whitelisted function isWhitelistedProxy(address _tokenTransferProxy) external view returns (bool) { return accounts[_tokenTransferProxy].groups[true].proxy; } /// @dev Provides the address of the exchange adapter /// @param _exchange Address of the exchange /// @return Address of the adapter function getExchangeAdapter(address _exchange) external view returns (address) { return blocks.adapter[_exchange]; } /// @dev Provides the address of the signature verifier /// @return Address of the verifier function getSigVerifier() external view returns (address) { return blocks.sigVerifier; } /// @dev Checkes whether a token is allowed on an exchange /// @param _token Address of the token /// @param _exchange Address of the exchange /// @return Bool the token is whitelisted on the exchange function canTradeTokenOnExchange(address _token, address _exchange) external view returns (bool) { return blocks.allowedTokens[_exchange][_token]; } /// @dev Checkes whether a token is allowed on a wrapper /// @param _token Address of the token /// @param _wrapper Address of the token wrapper /// @return Bool the token is whitelisted on the exchange function canWrapTokenOnWrapper(address _token, address _wrapper) external view returns (bool) { return blocks.allowedWrappers[_wrapper][_token]; } /// @dev Checkes whether a method is allowed on an exchange /// @param _method Bytes of the function signature /// @param _adapter Address of the exchange /// @return Bool the method is allowed function isMethodAllowed(bytes4 _method, address _adapter) external view returns (bool) { return blocks.allowedMethods[_adapter][_method]; } /// @dev Checkes whether casper has been inizialized /// @return Bool the casper contract has been initialized function isCasperInitialized() external view returns (bool) { address casper = blocks.casper; return blocks.initialized[casper]; } /// @dev Provides the address of the casper contract /// @return Address of the casper contract function getCasper() external view returns (address) { return blocks.casper; } /* * INTERNAL FUNCTIONS */ /// @dev Allows to whitelist an authority /// @param _authority Address of the authority /// @param _isWhitelisted Bool whitelisted function setAuthorityInternal( address _authority, bool _isWhitelisted) internal { accounts[_authority].account = _authority; accounts[_authority].authorized = _isWhitelisted; accounts[_authority].groups[_isWhitelisted].authority = _isWhitelisted; setWhitelisterInternal(_authority, _isWhitelisted); types.list.push(List(_authority)); emit AuthoritySet(_authority); } /// @dev Allows the owner to whitelist a whitelister /// @param _whitelister Address of the whitelister /// @param _isWhitelisted Bool whitelisted function setWhitelisterInternal( address _whitelister, bool _isWhitelisted) internal { accounts[_whitelister].account = _whitelister; accounts[_whitelister].authorized = _isWhitelisted; accounts[_whitelister].groups[_isWhitelisted].whitelister = _isWhitelisted; types.list.push(List(_whitelister)); emit WhitelisterSet(_whitelister); } /// @dev Provides whether an address is whitelister /// @param _whitelister Address of the target whitelister /// @return Bool is whitelisted function isWhitelister(address _whitelister) internal view returns (bool) { return accounts[_whitelister].groups[true].whitelister; } }
Provides whether a token wrapper is whitelisted _wrapper Address of the target exchange return Bool is whitelisted
function isWhitelistedWrapper(address _wrapper) external view returns (bool) { return accounts[_wrapper].groups[true].wrapper; }
980,967
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import './BitMath.sol'; /// @title Packed tick initialized state library /// @notice Stores a packed mapping of tick index to its initialized state /// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word. library TickBitmap { /// @notice Computes the position in the mapping where the initialized bit for a tick lives /// @param tick The tick for which to compute the position /// @return wordPos The key in the mapping containing the word in which the bit is stored /// @return bitPos The bit position in the word where the flag is stored function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) { wordPos = int16(tick >> 8); bitPos = uint8(uint24(tick % 256)); } /// @notice Flips the initialized state for a given tick from false to true, or vice versa /// @param self The mapping in which to flip the tick /// @param tick The tick to flip /// @param tickSpacing The spacing between usable ticks function flipTick( mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing ) internal { require(tick % tickSpacing == 0); // ensure that the tick is spaced (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing); uint256 mask = 1 << bitPos; self[wordPos] ^= mask; } /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either /// to the left (less than or equal to) or right (greater than) of the given tick /// @param self The mapping in which to compute the next initialized tick /// @param tick The starting tick /// @param tickSpacing The spacing between usable ticks /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick) /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks function nextInitializedTickWithinOneWord( mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing, bool lte ) internal view returns (int24 next, bool initialized) { int24 compressed = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity if (lte) { (int16 wordPos, uint8 bitPos) = position(compressed); // all the 1s at or to the right of the current bitPos uint256 mask = (1 << bitPos) - 1 + (1 << bitPos); uint256 masked = self[wordPos] & mask; // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing : (compressed - int24(uint24(bitPos))) * tickSpacing; } else { // start from the word of the next tick, since the current tick state doesn't matter (int16 wordPos, uint8 bitPos) = position(compressed + 1); // all the 1s at or to the left of the bitPos uint256 mask = ~((1 << bitPos) - 1); uint256 masked = self[wordPos] & mask; // if there are no initialized ticks to the left of the current tick, return leftmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed + 1 + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing : (compressed + 1 + int24(uint24(type(uint8).max - bitPos))) * tickSpacing; } } }
Computes the position in the mapping where the initialized bit for a tick lives tick The tick for which to compute the position return wordPos The key in the mapping containing the word in which the bit is stored return bitPos The bit position in the word where the flag is stored
function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) { wordPos = int16(tick >> 8); bitPos = uint8(uint24(tick % 256)); }
897,388
pragma solidity ^0.6.0; /** Powered by Paul Bolhar t.me/bolpol Smart solutions and code audit. http://pironmind.com */ /** @title ERC20 interface (short version) */ interface ERC20 { function balanceOf(address tokenOwner) external returns (uint balance); function transfer(address to, uint tokens) external returns (bool success); } /** @title Owned - ownership */ contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } /** @title Airdropper - using for package token transfer */ contract Airdropper is Owned { ERC20 public token; event Airdropped(bool indexed ok); event Destroyed(uint indexed time); /** * @dev Constructor. * @param tokenAddress Address of the token contract. */ constructor(address tokenAddress) public { token = ERC20(tokenAddress); } // + 10-20 gas lie function test(address[] memory dests, uint[] memory values) public { uint startGas = gasleft(); airdrop(dests, values); uint gasUsed = startGas - gasleft(); log1(bytes32(block.gaslimit), 'gaslimit'); log1(bytes32(gasUsed), 'gasUsed'); revert(); } /** * @dev Airdrop. * @ !important Before using, send needed token amount to this contract */ function airdrop(address[] memory dests, uint[] memory values) public onlyOwner { // This simple validation will catch most mistakes without consuming // too much gas. require(dests.length == values.length); for (uint256 i = 0; i < dests.length; i++) { token.transfer(dests[i], values[i]); } emit Airdropped(true); } /** * @dev Return all tokens back to owner, in case any were accidentally * transferred to this contract. */ function returnTokens() public onlyOwner returns(bool) { return token.transfer(owner, token.balanceOf(address(this))); } /** * @dev Destroy this contract and recover any ether to the owner. */ function destroy() public onlyOwner { if(returnTokens()) { emit Destroyed(now); selfdestruct(msg.sender); } } }
Destroy this contract and recover any ether to the owner./
function destroy() public onlyOwner { if(returnTokens()) { emit Destroyed(now); selfdestruct(msg.sender); } }
6,411,689
// SPDX-License-Identifier: Unlicensed pragma solidity 0.8.7; /** * @title SafeMath * @dev 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 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 ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ abstract contract ERC20Basic { function totalSupply() external view virtual returns (uint256); function balanceOf(address who) external view virtual returns (uint256); function transfer(address to, uint256 value) external virtual returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() external view override returns(uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) external override returns(bool) { require(_to != address(0), "Recipient is zero address"); require(_value <= balances[msg.sender], "Not enough balance"); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) external view override returns(uint256) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ abstract contract ERC20 is ERC20Basic { function allowance(address owner, address spender) external view virtual returns (uint256); function transferFrom(address from, address to, uint256 value) external virtual returns (bool); function approve(address spender, uint256 value) external virtual returns(bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ contract StandardToken is ERC20, BasicToken { using SafeMath for uint256; mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) external override returns (bool) { require(_to != address(0), "Recipient is zero address"); require(_value <= balances[_from], "Not enough balance"); require(_value <= allowed[_from][msg.sender], "Not enough allowance"); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) external override returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) external override view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) external returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) external returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } contract Owned { address public owner; constructor() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner, "Ownable: caller is not the owner."); _; } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Owned { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; address internal ownerShip; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable, address _realOwner ) { require(_beneficiary != address(0), "beneficiary is a zero address"); require(_realOwner != address(0), "real owner is a zero address"); require(_cliff <= _duration, "cliff timing should be less than duration"); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; ownerShip = _realOwner; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0, "Unreleased should be greater than zero"); released[address(token)] = released[address(token)].add(unreleased); token.safeTransfer(beneficiary, unreleased); emit Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) external onlyOwner { require(revocable, "Should be revocable"); require(!revoked[address(token)], "Should not be revoked"); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[address(token)] = true; token.safeTransfer(ownerShip, refund); emit Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[address(token)]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(released[address(token)]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[address(token)]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } /** * @title TokenVault * @dev TokenVault is a token holder contract that will allow a * beneficiary to spend the tokens from some function of a specified ERC20 token */ contract TokenVault { using SafeERC20 for ERC20; // ERC20 token contract being held ERC20 public token; constructor(ERC20 _token) { require(address(_token) != address(0), "Token is zero address"); token = _token; } /** * @notice Allow the token itself to send tokens * using transferFrom(). */ function fillUpAllowance() external returns(bool){ uint256 amount = token.balanceOf(address(this)); require(amount > 0, "Amount is zero"); token.approve(address(token), amount); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { using SafeMath for uint256; event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) external { require(_value > 0, "value is zero"); require(_value <= balances[msg.sender], "Not enough balance"); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(burner, _value); } } contract OndaToken is BurnableToken, Owned { using SafeMath for uint256; string public constant name = "ONDA TOKEN"; string public constant symbol = "ONDA"; uint8 public constant decimals = 18; /// Maximum tokens to be allocated ( 1 billion ONDA ) uint256 public constant HARD_CAP = 10**9 * 10**uint256(decimals); /// This address will be used to distribute the team, advisors and reserve tokens address public saleTokensAddress; /// This vault is used to keep the Founders, Advisors and Partners tokens TokenVault public reserveTokensVault; // Date when the vesting for regular users starts uint64 internal constant daySecond = 86400; uint64 internal constant lock90Days = 90; uint64 internal constant unlock100Days = 100; uint64 internal constant lock365Days = 365; /// Store the vesting contract addresses for each sale contributor mapping(address => address) public vestingOf; event CreatedTokenVault(address indexed account, uint256 value); event VestedTokenDetails(address indexed _beneficiary, uint256 _startS, uint256 _cliffS, uint256 _durationS, bool _revocable, uint256 _tokensAmountInt); event VestedTokenStartAt(address _beneficiary, uint256 _tokensAmountInt, uint256 _startS, uint256 _afterDay, uint256 _cliffDay, uint256 _durationDay); constructor(address _saleTokensAddress) { require(_saleTokensAddress != address(0), "OndaToken: zero address"); saleTokensAddress = _saleTokensAddress; /// Maximum tokens to be sold - 369 million, tokenomics will be distributed from sale wallet createTokensInt(369 * 10**6, saleTokensAddress); } /// @dev Create a ReserveTokenVault function createReserveTokensVault() external onlyOwner { require(address(reserveTokensVault) == address(0), "OndaToken: reserve token vault is zero address"); /// Reserve tokens - 631 million reserveTokensVault = createTokenVaultInt(631*10**6); } /// @dev Create a TokenVault and fill with the specified newly minted tokens function createTokenVaultInt(uint256 tokens) internal returns (TokenVault) { TokenVault tokenVault = new TokenVault(ERC20(this)); createTokensInt(tokens, address(tokenVault)); tokenVault.fillUpAllowance(); emit CreatedTokenVault(address(this), tokens); return tokenVault; } // @dev create specified number of tokens and transfer to destination function createTokensInt(uint256 _tokens, address _destination) internal { uint256 tokens = _tokens * 10**uint256(decimals); totalSupply_ = totalSupply_.add(tokens); balances[_destination] = balances[_destination].add(tokens); emit Transfer(address(0), _destination, tokens); require(totalSupply_ <= HARD_CAP, "OndaToken: hard cap reached"); } /// @dev vest Detail : second unit function vestTokensDetailInt( address _beneficiary, uint256 _startS, uint256 _cliffS, uint256 _durationS, bool _revocable, uint256 _tokensAmountInt) external onlyOwner { require(_beneficiary != address(0), "beneficiary is zero address"); uint256 tokensAmount = _tokensAmountInt * 10**uint256(decimals); if(vestingOf[_beneficiary] == address(0)) { TokenVesting vesting = new TokenVesting(_beneficiary, _startS, _cliffS, _durationS, _revocable, owner); vestingOf[_beneficiary] = address(vesting); } emit VestedTokenDetails(_beneficiary, _startS, _cliffS, _durationS, _revocable, _tokensAmountInt); require(this.transferFrom(address(reserveTokensVault), vestingOf[_beneficiary], tokensAmount), "transfer from failed"); } /// @dev vest StartAt : day unit function vestTokensStartAtInt( address _beneficiary, uint256 _tokensAmountInt, uint256 _startS, uint256 _afterDay, uint256 _cliffDay, uint256 _durationDay ) public onlyOwner { require(_beneficiary != address(0), "beneficiary is zero address"); uint256 tokensAmount = _tokensAmountInt * 10**uint256(decimals); uint256 afterSec = _afterDay * daySecond; uint256 cliffSec = _cliffDay * daySecond; uint256 durationSec = _durationDay * daySecond; if(vestingOf[_beneficiary] == address(0)) { TokenVesting vesting = new TokenVesting(_beneficiary, _startS + afterSec, cliffSec, durationSec, true, owner); vestingOf[_beneficiary] = address(vesting); } emit VestedTokenStartAt(_beneficiary, _tokensAmountInt, _startS, _afterDay, _cliffDay, _durationDay); require(this.transferFrom(address(reserveTokensVault), vestingOf[_beneficiary], tokensAmount), "transfer from failed"); } /// @dev vest function from now function vestTokensFromNowInt(address _beneficiary, uint256 _tokensAmountInt, uint256 _afterDay, uint256 _cliffDay, uint256 _durationDay ) public onlyOwner { vestTokensStartAtInt(_beneficiary, _tokensAmountInt, block.timestamp, _afterDay, _cliffDay, _durationDay); } /// @dev vest the sale contributor tokens for 100 days, 1% gradual release function vestCmdNow1PercentInt(address _beneficiary, uint256 _tokensAmountInt) external onlyOwner { vestTokensFromNowInt(_beneficiary, _tokensAmountInt, 0, 0, unlock100Days); } /// @dev vest the sale contributor tokens for 100 days, 1% gradual release after 3 month later, no cliff function vestCmd3Month1PercentInt(address _beneficiary, uint256 _tokensAmountInt) external onlyOwner { vestTokensFromNowInt(_beneficiary, _tokensAmountInt, lock90Days, 0, unlock100Days); } /// @dev vest the sale contributor tokens 100% release after 1 year function vestCmd1YearInstantInt(address _beneficiary, uint256 _tokensAmountInt) external onlyOwner { vestTokensFromNowInt(_beneficiary, _tokensAmountInt, 0, lock365Days, lock365Days); } /// @dev releases vested tokens for the caller's own address function releaseVestedTokens() external { releaseVestedTokensFor(msg.sender); } /// @dev releases vested tokens for the specified address. /// Can be called by anyone for any address. function releaseVestedTokensFor(address _owner) public { TokenVesting(vestingOf[_owner]).release(this); } /// @dev check the vested balance for an address function lockedBalanceOf(address _owner) external view returns (uint256) { return balances[vestingOf[_owner]]; } /// @dev check the locked but releaseable balance of an owner function releaseableBalanceOf(address _owner) public view returns (uint256) { if (vestingOf[_owner] == address(0) ) { return 0; } else { return TokenVesting(vestingOf[_owner]).releasableAmount(this); } } /// @dev revoke vested tokens for the specified address. /// Tokens already vested remain in the contract, the rest are returned to the owner. function revokeVestedTokensFor(address _owner) external onlyOwner { TokenVesting(vestingOf[_owner]).revoke(this); } /// @dev Create a ReserveTokenVault function makeReserveToVault() external onlyOwner { require(address(reserveTokensVault) != address(0), "reserve token vault is zero address"); reserveTokensVault.fillUpAllowance(); } }
vest function from now
function vestTokensFromNowInt(address _beneficiary, uint256 _tokensAmountInt, uint256 _afterDay, uint256 _cliffDay, uint256 _durationDay ) public onlyOwner { vestTokensStartAtInt(_beneficiary, _tokensAmountInt, block.timestamp, _afterDay, _cliffDay, _durationDay); }
1,016,400
./partial_match/1/0xCF0aC4329820A2C3BBdFA7C1e3B4819662A85DcC/sources/contracts/RefToken.sol
has the pot been reached
function hasPotBeenReached() public view returns (bool) { return _potEthBalance >= _potWinningAmount; }
9,358,585
./full_match/1/0x911a768fF40e6477736AA009EF0055563982bE3a/sources/src/ExternalRefinancing.sol
Reads the int56 at `cdPtr` in calldata.
function readInt56( CalldataPointer cdPtr ) internal pure returns (int56 value) { assembly { value := calldataload(cdPtr) } }
3,218,330
pragma solidity 0.8.0; // SPDX-License-Identifier: MIT import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./eTacoToken.sol"; import "./interfaces/ILiquidityProvider.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; interface IMigrator { // Perform LP token migration from legacy UniswapV2 to TacoSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // TacoSwap must mint EXACTLY the same amount of TacoSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } /** * @title eTacoChef is the master of eTaco * @notice eTacoChef contract: * - Users can: * # Deposit * # Harvest * # Withdraw * # SpeedStake */ contract eTacoChef is OwnableUpgradeable, ReentrancyGuardUpgradeable { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @notice Info of each user * @param amount: How many LP tokens the user has provided * @param rewardDebt: Reward debt. See explanation below * @dev Any point in time, the amount of eTacos entitled to a user but is pending to be distributed is: * pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt * Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: * 1. The pool's `accRewardPerShare` (and `lastRewardBlock`) gets updated. * 2. User receives the pending reward sent to his/her address. * 3. User's `amount` gets updated. * 4. User's `rewardDebt` gets updated. */ struct UserInfo { uint256 amount; uint256 rewardDebt; } /** * @notice Info of each pool * @param lpToken: Address of LP token contract * @param allocPoint: How many allocation points assigned to this pool. eTacos to distribute per block * @param lastRewardBlock: Last block number that eTacos distribution occurs * @param accRewardPerShare: Accumulated eTacos per share, times 1e12. See below */ struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. eTacos to distribute per block. uint256 lastRewardBlock; // Last block number that eTacos distribution occurs. uint256 accRewardPerShare; // Accumulated eTacos per share, times 1e12. See below. } /// The eTaco TOKEN! eTacoToken public etaco; /// Dev address. address public devaddr; /// The Liquidity Provider ILiquidityProvider public provider; /// Block number when bonus eTaco period ends. uint256 public endBlock; /// eTaco tokens created in first block. uint256 public rewardPerBlock; /// The migrator contract. Can only be set through governance (owner). IMigrator public migrator; /// Info of each pool. PoolInfo[] public poolInfo; /// Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; mapping(address => bool) public isPoolExist; /// Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; /// The block number when eTaco mining starts. uint256 public startBlock; uint256 private _apiID; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event Provider(address oldProvider, address newProvider); event Api(uint256 id); event Migrator(address migratorAddress); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); modifier validatePoolByPid(uint256 _pid) { require(_pid < poolInfo.length, "Pool does not exist"); _; } function initialize( eTacoToken _etaco, uint256 _rewardPerBlock, uint256 _startBlock ) public initializer { __Ownable_init(); __ReentrancyGuard_init(); require(address(_etaco) != address(0x0), "eTacoChef::set zero address"); etaco = _etaco; devaddr = msg.sender; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; } /// @return All pools amount function poolLength() external view returns (uint256) { return poolInfo.length; } /** * @notice Function for set provider. Can be set by the owner * @param _provider: address of liquidity provider contract */ function setProvider(address payable _provider) external onlyOwner { require(_provider != address(0x0), "eTacoChef::set zero address"); emit Provider(address(provider), _provider); provider = ILiquidityProvider(_provider); } /** * @notice Function for set apiID. Can be set by the owner * @param _id: Api ID in liquidity provider contract */ function setApi(uint256 _id) external onlyOwner { _apiID = _id; emit Api(_id); } /** * @notice Add a new lp to the pool. Can only be called by the owner * @param _allocPoint: allocPoint for new pool * @param _lpToken: address of lpToken for new pool * @param _withUpdate: if true, update all pools */ function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { require( !isPoolExist[address(_lpToken)], "eTacoChef:: LP token already added" ); 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 }) ); isPoolExist[address(_lpToken)] = true; } /** * @notice Update the given pool's eTaco allocation point. Can only be called by the owner */ function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner validatePoolByPid(_pid) { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } /** * @notice Set the migrator contract. Can only be called by the owner * @param _migrator: migrator contract */ function setMigrator(IMigrator _migrator) public onlyOwner { migrator = _migrator; emit Migrator(address(_migrator)); } /** * @notice Migrate lp token to another lp contract. Can be called by anyone * @param _pid: ID of pool which message sender wants to migrate */ function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } /** * @notice Reward decreases with each block * @param _block: block number for which the reward should be calculated * @return Returns reward for _block */ function getRewardForBlock(uint256 _block) public view returns (uint256) { return rewardPerBlock.sub( _block.sub(startBlock).mul(rewardPerBlock).div( endBlock.sub(startBlock) ) ); } /** * @param _from: block number from which the reward is calculated * @param _to: block number before which the reward is calculated * @return Return reward multiplier over the given _from to _to block */ function getReward(uint256 _from, uint256 _to) public view returns (uint256) { return rewardPerBlock.mul(_to.sub(_from)); } /** * @notice View function to see pending eTacos on frontend * @param _pid: pool ID for which reward must be calculated * @param _user: user address for which reward must be calculated * @return Return reward for user */ function pendingReward(uint256 _pid, address _user) external view validatePoolByPid(_pid) returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getReward(pool.lastRewardBlock, block.number); uint256 etacoReward = multiplier.mul(pool.allocPoint).div( totalAllocPoint ); accRewardPerShare = accRewardPerShare.add( etacoReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt); } /** * @notice Update reward vairables for all pools */ function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } /** * @notice Update reward variables of the given pool to be up-to-date * @param _pid: pool ID for which the reward variables should be updated */ function updatePool(uint256 _pid) public validatePoolByPid(_pid) { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getReward(pool.lastRewardBlock, block.number); uint256 etacoReward = multiplier.mul(pool.allocPoint).div( totalAllocPoint ); safeETacoTransfer(devaddr, etacoReward.div(10)); // etacoReward = etacoReward.mul(9).div(10); // safeETacoTransfer(address(this), etacoReward); instant send 33% : 66% pool.accRewardPerShare = pool.accRewardPerShare.add( etacoReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } /** * @notice Deposit LP tokens to eTacoChef for eTaco allocation * @param _pid: pool ID on which LP tokens should be deposited * @param _amount: the amount of LP tokens that should be deposited */ function deposit(uint256 _pid, uint256 _amount) public validatePoolByPid(_pid) { updatePool(_pid); poolInfo[_pid].lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); _deposit(_pid, _amount); } /** * @notice Function for updating user info */ function _deposit(uint256 _pid, uint256 _amount) private { UserInfo storage user = userInfo[_pid][msg.sender]; harvest(_pid); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(poolInfo[_pid].accRewardPerShare).div( 1e12 ); emit Deposit(msg.sender, _pid, _amount); } /** * @notice Function which send accumulated eTaco tokens to messege sender * @param _pid: pool ID from which the accumulated eTaco tokens should be received */ function harvest(uint256 _pid) public validatePoolByPid(_pid) { UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 accRewardPerShare = poolInfo[_pid].accRewardPerShare; uint256 accumulatedeTaco = user.amount.mul(accRewardPerShare).div(1e12); uint256 pending = accumulatedeTaco.sub(user.rewardDebt); safeETacoTransfer(msg.sender, pending); user.rewardDebt = user.amount.mul(accRewardPerShare).div(1e12); emit Harvest(msg.sender, _pid, pending); } /** * @notice Function which send accumulated eTaco tokens to messege sender from all pools */ function harvestAll() public { uint256 length = poolInfo.length; for (uint256 i = 0; i < length; i++) { harvest(i); } } /** * @notice Function which withdraw LP tokens to messege sender with the given amount * @param _pid: pool ID from which the LP tokens should be withdrawn * @param _amount: the amount of LP tokens that should be withdrawn */ function withdraw(uint256 _pid, uint256 _amount) public validatePoolByPid(_pid) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accRewardPerShare).div(1e12).sub( user.rewardDebt ); safeETacoTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } /** * @notice Function which withdraw all LP tokens to messege sender without caring about rewards */ function emergencyWithdraw(uint256 _pid) public validatePoolByPid(_pid) nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } /** * @notice Function which transfer eTaco tokens to _to with the given amount * @param _to: transfer reciver address * @param _amount: amount of eTaco token which should be transfer */ function safeETacoTransfer(address _to, uint256 _amount) internal { uint256 etacoBal = etaco.balanceOf(address(this)); if (_amount > etacoBal) { etaco.transfer(_to, etacoBal); } else { etaco.transfer(_to, _amount); } } /** * @notice Function which should be update dev address by the previous dev * @param _devaddr: new dev address */ function dev(address _devaddr) public { require(msg.sender == devaddr, "eTacoCHef: dev wut?"); require(_devaddr == address(0), "eTacoCHef: dev address can't be zero"); devaddr = _devaddr; } /** * @notice Function which take ETH, add liquidity with provider and deposit given LP's * @param _pid: pool ID where we want deposit * @param _amountAMin: bounds the extent to which the B/A price can go up before the transaction reverts. Must be <= amountADesired. * @param _amountBMin: bounds the extent to which the A/B price can go up before the transaction reverts. Must be <= amountBDesired * @param _minAmountOutA: the minimum amount of output A tokens that must be received for the transaction not to revert * @param _minAmountOutB: the minimum amount of output B tokens that must be received for the transaction not to revert */ function speedStake( uint256 _pid, uint256 _amountAMin, uint256 _amountBMin, uint256 _minAmountOutA, uint256 _minAmountOutB, uint256 _deadline ) public payable validatePoolByPid(_pid) { (address routerAddr, , ) = provider.apis(_apiID); IUniswapV2Router02 router = IUniswapV2Router02(routerAddr); delete routerAddr; require( address(router) != address(0), "MasterChef: Exchange does not set yet" ); PoolInfo storage pool = poolInfo[_pid]; uint256 lp; updatePool(_pid); IUniswapV2Pair lpToken = IUniswapV2Pair(address(pool.lpToken)); if ( (lpToken.token0() == router.WETH()) || ((lpToken.token1() == router.WETH())) ) { lp = provider.addLiquidityETHByPair{value: msg.value}( lpToken, address(this), _amountAMin, _amountBMin, _minAmountOutA, _deadline, _apiID ); } else { lp = provider.addLiquidityByPair{value: msg.value}( lpToken, _amountAMin, _amountBMin, _minAmountOutA, _minAmountOutB, address(this), _deadline, _apiID ); } _deposit(_pid, lp); } /** * @notice Function which migrate pool to eTacoChef. Can only be called by the migrator */ function setPool( IERC20 _lpToken, uint256 _allocPoint, uint256 _lastRewardBlock, uint256 _accRewardPerShare ) public { require( msg.sender == address(migrator), "eTacoChef: Only migrator can call" ); poolInfo.push( PoolInfo( IERC20(_lpToken), _allocPoint, _lastRewardBlock, _accRewardPerShare.mul(9).div(10) ) ); totalAllocPoint += _allocPoint; } /** * @notice Function which migrate user to eTacoChef */ function setUser( uint256 _pid, address _user, uint256 _amount, uint256 _rewardDebt ) public { require( msg.sender == address(migrator), "eTacoChef: Only migrator can call" ); require(poolInfo.length != 0, "eTacoChef: Pools must be migrated"); updatePool(_pid); userInfo[_pid][_user] = UserInfo(_amount, _rewardDebt.mul(9).div(10)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } pragma solidity 0.8.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT contract eTacoToken { /// @notice EIP-20 token name for this token string public constant name = "eTACO Token"; /// @notice EIP-20 token symbol for this token string public constant symbol = "eTACO"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public constant totalSupply = 395097860e18; // 395,097,860 million eTaco /// @dev Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @dev Official record of token balances for each account mapping (address => uint96) internal balances; /// @dev A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new eTaco token */ constructor() { balances[msg.sender] = uint96(totalSupply); emit Transfer(address(0), msg.sender, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; } else { amount = safe96(rawAmount, "eTacoToken::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "eTacoToken::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "eTacoToken::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != type(uint96).max) { uint96 newAllowance = sub96(spenderAllowance, amount, "eTacoToken::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "eTacoToken::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "eTacoToken::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "eTacoToken::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "eTacoToken::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "eTacoToken::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "eTacoToken::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "eTacoToken::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "eTacoToken::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "eTacoToken::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "eTacoToken::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "eTacoToken::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal view returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity >=0.6.12 <0.9.0; // SPDX-License-Identifier: UNLICENSED import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; interface ILiquidityProvider { function apis(uint256) external view returns(address, address, address); function addExchange(IUniswapV2Router02) external; function addLiquidityETH( address, address, uint256, uint256, uint256, uint256, uint256 ) external payable returns (uint256); function addLiquidityETHByPair( IUniswapV2Pair, address, uint256, uint256, uint256, uint256, uint256 ) external payable returns (uint256); function addLiquidity( address, address, uint256, uint256, uint256, uint256, address, uint256, uint256 ) external payable returns (uint256); function addLiquidityByPair( IUniswapV2Pair, uint256, uint256, uint256, uint256, address, uint256, uint256 ) external payable returns (uint256); function removeLiquidityETH( address, uint256, uint256, uint256, uint256, address, uint256, uint256, uint8 ) external returns (uint256[3] memory); function removeLiquidityETHByPair( IUniswapV2Pair, uint256, uint256, uint256, uint256, address, uint256, uint256, uint8 ) external returns (uint256[3] memory); function removeLiquidityETHWithPermit( address, uint256, uint256, uint256, uint256, address, uint256, uint256, uint8, uint8, bytes32, bytes32 ) external returns (uint256[3] memory); function removeLiquidity( address, address, uint256, uint256[2] memory, uint256[2] memory, address, uint256, uint256, uint8 ) external returns (uint256[3] memory); function removeLiquidityByPair( IUniswapV2Pair, uint256, uint256[2] memory, uint256[2] memory, address, uint256, uint256, uint8 ) external returns (uint256[3] memory); function removeLiquidityWithPermit( address, address, uint256, uint256[2] memory, uint256[2] memory, address, uint256, uint256, uint8, uint8, bytes32, bytes32 ) external returns (uint256[3] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/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.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 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; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } 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; 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; } 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { 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 // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } }
_from: block number from which the reward is calculated _to: block number before which the reward is calculated return Return reward multiplier over the given _from to _to block/
function getReward(uint256 _from, uint256 _to) public view returns (uint256) { return rewardPerBlock.mul(_to.sub(_from)); }
14,913,590
// SPDX-License-Identifier: MIT import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; pragma solidity ^0.8.0; contract Byoa is ERC721Enumerable, AccessControl, ERC721URIStorage { using Counters for Counters.Counter; Counters.Counter private _byoaAppIds; // Role for developers to be able to mint apps bytes32 public constant DEVELOPER_ROLE = keccak256("DEVELOPER_ROLE"); bool private _requireDeveloperOnboarding = true; // Need a type to hold multiple types of byoa struct App { uint256 id; string name; string description; uint256 price; string tokenURI; address owner; } // Mapping AppIds to the App mapping (uint256 => App) private apps; mapping (uint256 => bool) private approvalsByAppId; mapping (uint256 => uint256) private nftsToAppIds; mapping (uint256 => mapping (string => string)) private tokenIdPreferencesMap; mapping (uint256 => string[]) private tokenIdPreferenceKeys; constructor() ERC721("Byoa V1", "BYOA_V1") { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } function compareStrings(string memory a, string memory b) public pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } function updatePreferences(uint256 _tokenID, string memory key, string memory value) public { require(_exists(_tokenID), "Token ID must exist"); require(ownerOf(_tokenID) == msg.sender, "The owner must be the one attempting the update"); tokenIdPreferencesMap[_tokenID][key] = value; string[] memory keys = tokenIdPreferenceKeys[_tokenID]; for (uint256 i = 0; i < keys.length; i ++) { if (compareStrings(keys[i],key)) return; } tokenIdPreferenceKeys[_tokenID].push(key); } function getPreferencesKeys(uint256 _tokenId) public view returns (string[] memory) { require(_exists(_tokenId), "Token ID must exist to get preferences"); return tokenIdPreferenceKeys[_tokenId]; } function getPreferenceByKey(uint256 _tokenId, string memory key) public view returns (string memory) { require(_exists(_tokenId), "Token ID must exist to get preferences"); return tokenIdPreferencesMap[_tokenId][key]; } function mint(uint256 _appId) public payable { require(apps[_appId].id != 0, "App ID must exist"); uint256 totalSupply = totalSupply(); // Mint and increase the tokenID uint256 _tokenId = totalSupply + 1; _safeMint(msg.sender, _tokenId); require(_exists(_tokenId)); nftsToAppIds[_tokenId] = _appId; // Set the tokenURI to the URI specified by the App _setTokenURI(_tokenId, apps[_appId].tokenURI); } function getAppIdByTokenId(uint256 _tokenId) public view returns (uint256) { return nftsToAppIds[_tokenId]; } function createApp(string memory name, string memory description, uint256 price, string memory _tokenURI) public returns (uint256) { require(hasRole(DEVELOPER_ROLE, msg.sender) || (_requireDeveloperOnboarding == false), "Must be a developer to create an app"); _byoaAppIds.increment(); uint256 _appId = _byoaAppIds.current(); approvalsByAppId[_appId] = true; apps[_appId] = App({ id: _appId, name: name, description: description, price: price, tokenURI: _tokenURI, owner: msg.sender }); return _appId; } function setApprovalByAppId(uint256 _appId, bool _appr) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Must be an admin to change any approvals"); approvalsByAppId[_appId] = _appr; } function getApprovalByAppId(uint256 _appId) public view returns (bool) { return approvalsByAppId[_appId]; } function updateApp(uint256 appId, string memory name, string memory description, uint256 price, string memory _tokenURI) public returns (uint256) { require(hasRole(DEVELOPER_ROLE, msg.sender), "Must be a developer to create an app"); require(apps[appId].id != 0, "App ID must exist"); App memory app = apps[appId]; require(app.owner == msg.sender, "You must be the owner of this app"); apps[appId] = App({ id: appId, name: name, description: description, price: price, tokenURI: _tokenURI, owner: msg.sender }); return appId; } function getAppDetailsById(uint256 appId) public view returns ( string memory name, string memory description, string memory _tokenURI, address owner, uint256 price ) { require(apps[appId].id != 0, "App ID must exist"); App memory _app = apps[appId]; return (_app.name, _app.description, _app.tokenURI, _app.owner, _app.price); } function setDeveloperOnboarding(bool _shouldOnboard) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Must be an admin to set developer onboarding"); _requireDeveloperOnboarding = _shouldOnboard; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function getAppIds() public view returns (uint256[] memory) { uint256[] memory appIds = new uint256[](_byoaAppIds.current()); for (uint256 i=1; i <= _byoaAppIds.current(); i ++) { appIds[i-1] = i; } return appIds; } function withdrawAll() public payable { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Must be an admin to withdraw"); require(payable(msg.sender).send(address(this).balance)); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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 pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; }
Mint and increase the tokenID Set the tokenURI to the URI specified by the App
function mint(uint256 _appId) public payable { require(apps[_appId].id != 0, "App ID must exist"); uint256 totalSupply = totalSupply(); uint256 _tokenId = totalSupply + 1; _safeMint(msg.sender, _tokenId); require(_exists(_tokenId)); nftsToAppIds[_tokenId] = _appId; _setTokenURI(_tokenId, apps[_appId].tokenURI); }
13,686,733
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "../../access/Controllable.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, Initializable, Controllable { using Address for address; using Strings for uint256; event OwnershipTransferred(address indexed newOwner); address private _owner; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) internal _balances; uint256 _totalBalances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) internal _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string internal _uri; string internal _name; string internal _symbol; /** * @dev {_setURI} has been moved into {initialize_ERC1155} to support CREATE2 deploys */ constructor() { _addController(msg.sender); _owner = msg.sender; } function owner() external view returns(address owner_) { owner_ = _owner; } function transferOwnership(address _newOwner) external returns (bool _success) { _owner = _newOwner; emit OwnershipTransferred(_owner); return true; } function renounceOwnership() external returns (bool _success) { _owner = address(0); emit OwnershipTransferred(_owner); return true; } /** * @dev See {_setURI}. */ function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function setName(string memory name_) public onlyController { _name = name_; } function setSymbol(string memory symbol_) public onlyController { _symbol = symbol_; } function setUri(string memory uri_) public onlyController { _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 a fully-built URL * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256 tokenHash) public view virtual override returns (string memory) { return string(abi.encodePacked(_uri, tokenHash.toString())); } /** * @dev See {IERC1155-balanceOf}. * */ function contractURI() public view returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * */ function totalSupply() public view returns (uint256) { return _totalBalances; } /** * @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 { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { 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; } function setURI(string memory newuri) public { setURI(newuri); } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; _totalBalances += 1; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } function mint( uint256 id, uint256 amount, bytes memory data ) external onlyController returns (uint256 tokenHash) { _mint(msg.sender, id, amount, data); tokenHash = id; } function mintTo( address account, uint256 id, uint256 amount, bytes memory data ) external onlyController returns (uint256 tokenHash) { _mint(account, id, amount, data); tokenHash = id; } /** * @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); } function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external onlyController { _mintBatch(to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; _totalBalances -= 1; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } function burn( address account, uint256 id, uint256 amount ) external onlyController { _burn(account, 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 account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } function burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) external onlyController { _burnBatch(account, ids, amounts); } /** * @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 ) internal { 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 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/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 (last updated v4.5.0) (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. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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 (last updated v4.6.0-rc.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ``` * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * 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 prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`. */ modifier initializer() { bool isTopLevelCall = _setInitializedVersion(1); if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original * initialization step. This is essential to configure modules that are added through upgrades and that require * initialization. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. */ modifier reinitializer(uint8 version) { bool isTopLevelCall = _setInitializedVersion(version); if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(version); } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. */ function _disableInitializers() internal virtual { _setInitializedVersion(type(uint8).max); } function _setInitializedVersion(uint8 version) private returns (bool) { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, and for the lowest level // of initializers, because in other contexts the contract may have been reentered. if (_initializing) { require( version == 1 && !Address.isContract(address(this)), "Initializable: contract is already initialized" ); return false; } else { require(_initialized < version, "Initializable: contract is already initialized"); _initialized = version; return true; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../interfaces/IControllable.sol"; abstract contract Controllable is IControllable { mapping(address => bool) internal _controllers; /** * @dev Throws if called by any account not in authorized list */ modifier onlyController() { require( _controllers[msg.sender] == true || address(this) == msg.sender, "Controllable: caller is not a controller" ); _; } /** * @dev Add an address allowed to control this contract */ function addController(address _controller) external override onlyController { _addController(_controller); } function _addController(address _controller) internal { _controllers[_controller] = true; } /** * @dev Check if this address is a controller */ function isController(address _address) external view override returns (bool allowed) { allowed = _isController(_address); } function _isController(address _address) internal view returns (bool allowed) { allowed = _controllers[_address]; } /** * @dev Remove the sender address from the list of controllers */ function relinquishControl() external override onlyController { _relinquishControl(); } function _relinquishControl() internal onlyController{ delete _controllers[msg.sender]; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// @notice a controllable contract interface. allows for controllers to perform privileged actions. controllera can other controllers and remove themselves. interface IControllable { /// @notice emitted when a controller is added. event ControllerAdded( address indexed contractAddress, address indexed controllerAddress ); /// @notice emitted when a controller is removed. event ControllerRemoved( address indexed contractAddress, address indexed controllerAddress ); /// @notice adds a controller. /// @param controller the controller to add. function addController(address controller) external; /// @notice removes a controller. /// @param controller the address to check /// @return true if the address is a controller function isController(address controller) external view returns (bool); /// @notice remove ourselves from the list of controllers. function relinquishControl() external; }
xref:ROOT:erc1155.adocbatch-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); }
1,159,126
./partial_match/137/0x18ec0A6E18E5bc3784fDd3a3634b31245ab704F6/sources/contracts/IPolygonPosChildToken.sol
IPolygonPosChildToken This interface define the mandatory method enabling polygon bridging mechanism. This interface should be inherited to deploy on polygon POS network./
interface IPolygonPosChildToken { function deposit(address user, bytes calldata depositData) external; function withdraw(uint256 amount) external; pragma solidity ^0.8.0; }
3,531,860
// File: contracts/lib/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 * @dev A standard interface for tokens. * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract ERC20 { /// @dev Returns the total token supply function totalSupply() public view returns (uint256 supply); /// @dev Returns the account balance of the account with address _owner function balanceOf(address _owner) public view returns (uint256 balance); /// @dev Transfers _value number of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); /// @dev Transfers _value number of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @dev Allows _spender to withdraw from the msg.sender's account up to the _value amount function approve(address _spender, uint256 _value) public returns (bool success); /// @dev Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // File: contracts/FundsForwarder.sol interface IGivethBridge { function donate(uint64 giverId, uint64 receiverId) external payable; function donate(uint64 giverId, uint64 receiverId, address token, uint _amount) external payable; } interface IFundsForwarderFactory { function bridge() external returns (address); function escapeHatchCaller() external returns (address); function escapeHatchDestination() external returns (address); } interface IMolochDao { function approvedToken() external returns (address); function members(address member) external returns (address, uint256, bool, uint256); function ragequit(uint sharesToBurn) external; } interface IWEth { function withdraw(uint wad) external; function balanceOf(address guy) external returns (uint); } contract FundsForwarder { uint64 public receiverId; uint64 public giverId; IFundsForwarderFactory public fundsForwarderFactory; string private constant ERROR_ERC20_APPROVE = "ERROR_ERC20_APPROVE"; string private constant ERROR_BRIDGE_CALL = "ERROR_BRIDGE_CALL"; string private constant ERROR_ZERO_BRIDGE = "ERROR_ZERO_BRIDGE"; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_TOKEN_TRANSFER = "RECOVER_TOKEN_TRANSFER"; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; uint private constant MAX_UINT = uint(-1); event Forwarded(address to, address token, uint balance); event EscapeHatchCalled(address token, uint amount); constructor() public { /// @dev From AragonOS's Autopetrified contract // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). fundsForwarderFactory = IFundsForwarderFactory(address(-1)); } /** * Fallback function to receive ETH donations */ function() public payable {} /** * @dev Initialize can only be called once. * @notice msg.sender MUST be the _fundsForwarderFactory Contract * Its address must be a contract with three public getters: * - bridge(): Returns the bridge address * - escapeHatchCaller(): Returns the escapeHatchCaller address * - escapeHatchDestination(): Returns the escashouldpeHatchDestination address * @param _giverId The adminId of the liquidPledging pledge admin who is donating * @param _receiverId The adminId of the liquidPledging pledge admin receiving the donation */ function initialize(uint64 _giverId, uint64 _receiverId) public { /// @dev onlyInit method from AragonOS's Initializable contract require(fundsForwarderFactory == address(0), ERROR_ALREADY_INITIALIZED); /// @dev Setting fundsForwarderFactory, serves as calling initialized() fundsForwarderFactory = IFundsForwarderFactory(msg.sender); /// @dev Make sure that the fundsForwarderFactory is a contract and has a bridge method require(fundsForwarderFactory.bridge() != address(0), ERROR_ZERO_BRIDGE); receiverId = _receiverId; giverId = _giverId; } /** * Transfer tokens/eth to the bridge. Transfer the entire balance of the contract * @param _token the token to transfer. 0x0 for ETH */ function forward(address _token) public { IGivethBridge bridge = IGivethBridge(fundsForwarderFactory.bridge()); require(bridge != address(0), ERROR_ZERO_BRIDGE); uint balance; bool result; /// @dev Logic for ether if (_token == address(0)) { balance = address(this).balance; /// @dev Call donate() with two arguments, for tokens /// Low level .call must be used due to function overloading /// keccak250("donate(uint64,uint64)") = bde60ac9 /* solium-disable-next-line security/no-call-value */ result = address(bridge).call.value(balance)( 0xbde60ac9, giverId, receiverId ); /// @dev Logic for tokens } else { ERC20 token = ERC20(_token); balance = token.balanceOf(this); /// @dev Since the bridge is a trusted contract, the max allowance /// will be set on the first token transfer. Then it's skipped /// Numbers for DAI First tx | n+1 txs /// approve(_, balance) 66356 51356 /// approve(_, MAX_UINT) 78596 39103 /// +12240 -12253 /// Worth it if forward is called more than once for each token if (token.allowance(address(this), bridge) < balance) { require(token.approve(bridge, MAX_UINT), ERROR_ERC20_APPROVE); } /// @dev Call donate() with four arguments, for tokens /// Low level .call must be used due to function overloading /// keccak256("donate(uint64,uint64,address,uint256)") = 4c4316c7 /* solium-disable-next-line security/no-low-level-calls */ result = address(bridge).call( 0x4c4316c7, giverId, receiverId, token, balance ); } require(result, ERROR_BRIDGE_CALL); emit Forwarded(bridge, _token, balance); } /** * Transfer multiple tokens/eth to the bridge. Simplies UI interactions * @param _tokens the array of tokens to transfer. 0x0 for ETH */ function forwardMultiple(address[] _tokens) public { uint tokensLength = _tokens.length; for (uint i = 0; i < tokensLength; i++) { forward(_tokens[i]); } } /** * Transfer tokens from a Moloch DAO by calling ragequit on all shares * @param _molochDao Address of a Moloch DAO * @param _convertWeth Flag to indicate that this DAO uses WETH */ function forwardMoloch(address _molochDao, bool _convertWeth) public { IMolochDao molochDao = IMolochDao(_molochDao); (,uint shares,,) = molochDao.members(address(this)); molochDao.ragequit(shares); address approvedToken = molochDao.approvedToken(); if (_convertWeth) { IWEth weth = IWEth(approvedToken); weth.withdraw(weth.balanceOf(address(this))); forward(address(0)); } else { forward(molochDao.approvedToken()); } } /** * @notice Send funds to recovery address (escapeHatchDestination). * The `escapeHatch()` should only be called as a last resort if a * security issue is uncovered or something unexpected happened * @param _token Token balance to be sent to recovery vault. * * @dev Only the escapeHatchCaller can trigger this function * @dev The escapeHatchCaller address must not have control over escapeHatchDestination * @dev Function extracted from the Escapable contract (by Jordi Baylina and Adrià Massanet) * Instead of storing the caller, destination and owner addresses, * it fetches them from the parent contract. */ function escapeHatch(address _token) public { /// @dev Serves as the original contract's onlyEscapeHatchCaller require(msg.sender == fundsForwarderFactory.escapeHatchCaller(), ERROR_DISALLOWED); address escapeHatchDestination = fundsForwarderFactory.escapeHatchDestination(); uint256 balance; if (_token == 0x0) { balance = address(this).balance; escapeHatchDestination.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.balanceOf(this); require(token.transfer(escapeHatchDestination, balance), ERROR_TOKEN_TRANSFER); } emit EscapeHatchCalled(_token, balance); } } // File: contracts/lib/IsContract.sol /* * SPDX-License-Identitifer: MIT * Credit to @aragonOS */ contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: contracts/lib/Owned.sol /// @title Owned /// @author Adrià Massanet <[email protected]> /// @notice The Owned contract has an owner address, and provides basic /// authorization control functions, this simplifies & the implementation of /// user permissions; this contract has three work flows for a change in /// ownership, the first requires the new owner to validate that they have the /// ability to accept ownership, the second allows the ownership to be /// directly transfered without requiring acceptance, and the third allows for /// the ownership to be removed to allow for decentralization contract Owned { address public owner; address public newOwnerCandidate; event OwnershipRequested(address indexed by, address indexed to); event OwnershipTransferred(address indexed from, address indexed to); event OwnershipRemoved(); /// @dev The constructor sets the `msg.sender` as the`owner` of the contract constructor() public { owner = msg.sender; } /// @dev `owner` is the only address that can call a function with this /// modifier modifier onlyOwner() { require (msg.sender == owner,"err_ownedNotOwner"); _; } /// @dev In this 1st option for ownership transfer `proposeOwnership()` must /// be called first by the current `owner` then `acceptOwnership()` must be /// called by the `newOwnerCandidate` /// @notice `onlyOwner` Proposes to transfer control of the contract to a /// new owner /// @param _newOwnerCandidate The address being proposed as the new owner function proposeOwnership(address _newOwnerCandidate) public onlyOwner { newOwnerCandidate = _newOwnerCandidate; emit OwnershipRequested(msg.sender, newOwnerCandidate); } /// @notice Can only be called by the `newOwnerCandidate`, accepts the /// transfer of ownership function acceptOwnership() public { require(msg.sender == newOwnerCandidate,"err_ownedNotCandidate"); address oldOwner = owner; owner = newOwnerCandidate; newOwnerCandidate = 0x0; emit OwnershipTransferred(oldOwner, owner); } /// @dev In this 2nd option for ownership transfer `changeOwnership()` can /// be called and it will immediately assign ownership to the `newOwner` /// @notice `owner` can step down and assign some other address to this role /// @param _newOwner The address of the new owner function changeOwnership(address _newOwner) public onlyOwner { require(_newOwner != 0x0,"err_ownedInvalidAddress"); address oldOwner = owner; owner = _newOwner; newOwnerCandidate = 0x0; emit OwnershipTransferred(oldOwner, owner); } /// @dev In this 3rd option for ownership transfer `removeOwnership()` can /// be called and it will immediately assign ownership to the 0x0 address; /// it requires a 0xdece be input as a parameter to prevent accidental use /// @notice Decentralizes the contract, this operation cannot be undone /// @param _dac `0xdac` has to be entered for this function to work function removeOwnership(address _dac) public onlyOwner { require(_dac == 0xdac,"err_ownedInvalidDac"); owner = 0x0; newOwnerCandidate = 0x0; emit OwnershipRemoved(); } } // File: contracts/lib/Escapable.sol /* Copyright 2016, Jordi Baylina Contributor: Adrià Massanet <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @dev `Escapable` is a base level contract built off of the `Owned` /// contract; it creates an escape hatch function that can be called in an /// emergency that will allow designated addresses to send any ether or tokens /// held in the contract to an `escapeHatchDestination` as long as they were /// not blacklisted contract Escapable is Owned { address public escapeHatchCaller; address public escapeHatchDestination; mapping (address=>bool) private escapeBlacklist; // Token contract addresses /// @notice The Constructor assigns the `escapeHatchDestination` and the /// `escapeHatchCaller` /// @param _escapeHatchCaller The address of a trusted account or contract /// to call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal that `escapeHatchCaller` /// cannot move funds out of `escapeHatchDestination` /// @param _escapeHatchDestination The address of a safe location (usu a /// Multisig) to send the ether held in this contract; if a neutral address /// is required, the WHG Multisig is an option: /// 0x8Ff920020c8AD673661c8117f2855C384758C572 constructor(address _escapeHatchCaller, address _escapeHatchDestination) public { escapeHatchCaller = _escapeHatchCaller; escapeHatchDestination = _escapeHatchDestination; } /// @dev The addresses preassigned as `escapeHatchCaller` or `owner` /// are the only addresses that can call a function with this modifier modifier onlyEscapeHatchCallerOrOwner { require ( (msg.sender == escapeHatchCaller)||(msg.sender == owner), "err_escapableInvalidCaller" ); _; } /// @notice Creates the blacklist of tokens that are not able to be taken /// out of the contract; can only be done at the deployment, and the logic /// to add to the blacklist will be in the constructor of a child contract /// @param _token the token contract address that is to be blacklisted function blacklistEscapeToken(address _token) internal { escapeBlacklist[_token] = true; emit EscapeHatchBlackistedToken(_token); } /// @notice Checks to see if `_token` is in the blacklist of tokens /// @param _token the token address being queried /// @return False if `_token` is in the blacklist and can't be taken out of /// the contract via the `escapeHatch()` function isTokenEscapable(address _token) public view returns (bool) { return !escapeBlacklist[_token]; } /// @notice The `escapeHatch()` should only be called as a last resort if a /// security issue is uncovered or something unexpected happened /// @param _token to transfer, use 0x0 for ether function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner { require(escapeBlacklist[_token]==false,"err_escapableBlacklistedToken"); uint256 balance; /// @dev Logic for ether if (_token == 0x0) { balance = address(this).balance; escapeHatchDestination.transfer(balance); emit EscapeHatchCalled(_token, balance); return; } /// @dev Logic for tokens ERC20 token = ERC20(_token); balance = token.balanceOf(this); require(token.transfer(escapeHatchDestination, balance),"err_escapableTransfer"); emit EscapeHatchCalled(_token, balance); } /// @notice Changes the address assigned to call `escapeHatch()` /// @param _newEscapeHatchCaller The address of a trusted account or /// contract to call `escapeHatch()` to send the value in this contract to /// the `escapeHatchDestination`; it would be ideal that `escapeHatchCaller` /// cannot move funds out of `escapeHatchDestination` function changeHatchEscapeCaller(address _newEscapeHatchCaller) public onlyEscapeHatchCallerOrOwner { escapeHatchCaller = _newEscapeHatchCaller; } event EscapeHatchBlackistedToken(address token); event EscapeHatchCalled(address token, uint amount); } // File: contracts/FundsForwarderFactory.sol contract FundsForwarderFactory is Escapable, IsContract { address public bridge; address public childImplementation; string private constant ERROR_NOT_A_CONTRACT = "ERROR_NOT_A_CONTRACT"; string private constant ERROR_HATCH_CALLER = "ERROR_HATCH_CALLER"; string private constant ERROR_HATCH_DESTINATION = "ERROR_HATCH_DESTINATION"; event NewFundForwarder(address indexed _giver, uint64 indexed _receiverId, address fundsForwarder); event BridgeChanged(address newBridge); event ChildImplementationChanged(address newChildImplementation); /** * @notice Create a new factory for deploying Giveth FundForwarders * @dev Requires a deployed bridge * @param _bridge Bridge address * @param _escapeHatchCaller The address of a trusted account or contract to * call `escapeHatch()` to send the ether in this contract to the * `escapeHatchDestination` it would be ideal if `escapeHatchCaller` cannot move * funds out of `escapeHatchDestination` * @param _escapeHatchDestination The address of a safe location (usually a * Multisig) to send the value held in this contract in an emergency */ constructor( address _bridge, address _escapeHatchCaller, address _escapeHatchDestination, address _childImplementation ) Escapable(_escapeHatchCaller, _escapeHatchDestination) public { require(isContract(_bridge), ERROR_NOT_A_CONTRACT); bridge = _bridge; // Set the escapeHatch params to the same as in the bridge Escapable bridgeInstance = Escapable(_bridge); require(_escapeHatchCaller == bridgeInstance.escapeHatchCaller(), ERROR_HATCH_CALLER); require(_escapeHatchDestination == bridgeInstance.escapeHatchDestination(), ERROR_HATCH_DESTINATION); // Set the owner to the same as in the bridge changeOwnership(bridgeInstance.owner()); // Deploy FundsForwarder if (_childImplementation == address(0)) { childImplementation = new FundsForwarder(); } else { childImplementation = _childImplementation; } } /** * @notice Change the bridge address. * @param _bridge New bridge address */ function changeBridge(address _bridge) external onlyEscapeHatchCallerOrOwner { bridge = _bridge; emit BridgeChanged(_bridge); } /** * @notice Change the childImplementation address. * @param _childImplementation New childImplementation address */ function changeChildImplementation(address _childImplementation) external onlyEscapeHatchCallerOrOwner { childImplementation = _childImplementation; emit ChildImplementationChanged(_childImplementation); } /** * @param _giverId The adminId of the liquidPledging pledge admin who is donating * @param _receiverId The adminId of the liquidPledging pledge admin receiving the donation */ function newFundsForwarder(uint64 _giverId, uint64 _receiverId) public { address fundsForwarder = _deployMinimal(childImplementation); FundsForwarder(fundsForwarder).initialize(_giverId, _receiverId); // Store a registry of fundForwarders as events emit NewFundForwarder(_giverId, _receiverId, fundsForwarder); } /** * @notice Deploys a minimal forwarding proxy that is not upgradable * From ZepelinOS https://github.com/zeppelinos/zos/blob/v2.4.0/packages/lib/contracts/upgradeability/ProxyFactory.sol */ function _deployMinimal(address _logic) internal returns (address proxy) { // Adapted from https://github.com/optionality/clone-factory/blob/32782f82dfc5a00d103a7e61a17a5dedbd1e8e9d/contracts/CloneFactory.sol bytes20 targetBytes = bytes20(_logic); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) proxy := create(0, clone, 0x37) } } }
In this 1st option for ownership transfer `proposeOwnership()` must be called first by the current `owner` then `acceptOwnership()` must be called by the `newOwnerCandidate` `onlyOwner` Proposes to transfer control of the contract to a new owner _newOwnerCandidate The address being proposed as the new owner
function proposeOwnership(address _newOwnerCandidate) public onlyOwner { newOwnerCandidate = _newOwnerCandidate; emit OwnershipRequested(msg.sender, newOwnerCandidate); }
2,572,906
// File: contracts/SafeMath.sol pragma solidity ^0.5.0; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts/Address.sol pragma solidity ^0.5.0; /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: contracts/Common.sol pragma solidity ^0.5.0; /** Note: Simple contract to use as base for const vals */ contract CommonConstants { bytes4 constant internal ERC1155_ACCEPTED = 0xf23a6e61; // bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) bytes4 constant internal ERC1155_BATCH_ACCEPTED = 0xbc197c81; // bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")) } // File: contracts/IERC1155TokenReceiver.sol pragma solidity ^0.5.0; /** Note: The ERC-165 identifier for this interface is 0x4e2312e0. */ interface ERC1155TokenReceiver { /** @notice Handle the receipt of a single ERC1155 token type. @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated. This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer. This function MUST revert if it rejects the transfer. Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @param _operator The address which initiated the transfer (i.e. msg.sender) @param _from The address which previously owned the token @param _id The ID of the token being transferred @param _value The amount of tokens being transferred @param _data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4); /** @notice Handle the receipt of multiple ERC1155 token types. @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated. This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s). This function MUST revert if it rejects the transfer(s). Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @param _operator The address which initiated the batch transfer (i.e. msg.sender) @param _from The address which previously owned the token @param _ids An array containing ids of each token being transferred (order and length must match _values array) @param _values An array containing amounts of each token being transferred (order and length must match _ids array) @param _data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); } // File: contracts/ERC165.sol pragma solidity ^0.5.0; /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // File: contracts/IERC1155.sol pragma solidity ^0.5.0; /** @title ERC-1155 Multi Token Standard @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md Note: The ERC-165 identifier for this interface is 0xd9b67a26. */ interface IERC1155 /* is ERC165 */ { /** @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). The `_operator` argument MUST be msg.sender. The `_from` argument MUST be the address of the holder whose balance is decreased. The `_to` argument MUST be the address of the recipient whose balance is increased. The `_id` argument MUST be the token type being transferred. The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by. When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). */ event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); /** @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). The `_operator` argument MUST be msg.sender. The `_from` argument MUST be the address of the holder whose balance is decreased. The `_to` argument MUST be the address of the recipient whose balance is increased. The `_ids` argument MUST be the list of tokens being transferred. The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by. When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). */ event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values); /** @dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absense of an event assumes disabled). */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** @dev MUST emit when the URI is updated for a token ID. URIs are defined in RFC 3986. The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". */ event URI(string _value, uint256 indexed _id); /** @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if balance of holder for token `_id` is lower than the `_value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _id ID of the token type @param _value Transfer amount @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; /** @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if length of `_ids` is not the same as length of `_values`. MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. MUST revert on any other error. MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _ids IDs of each token type (order and length must match _values array) @param _values Transfer amounts per token type (order and length must match _ids array) @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external; /** @notice Get the balance of an account's Tokens. @param _owner The address of the token holder @param _id ID of the Token @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256); /** @notice Get the balance of multiple account/token pairs @param _owners The addresses of the token holders @param _ids ID of the Tokens @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); /** @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. @dev MUST emit the ApprovalForAll event on success. @param _operator Address to add to the set of authorized operators @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** @notice Queries the approval status of an operator for a given owner. @param _owner The owner of the Tokens @param _operator Address of authorized operator @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool); } // File: contracts/ERC1155.sol pragma solidity ^0.5.0; // A sample implementation of core ERC1155 function. contract ERC1155 is IERC1155, ERC165, CommonConstants { using SafeMath for uint256; using Address for address; // id => (owner => balance) mapping (uint256 => mapping(address => uint256)) internal balances; // owner => (operator => approved) mapping (address => mapping(address => bool)) internal operatorApproval; /////////////////////////////////////////// ERC165 ////////////////////////////////////////////// /* bytes4(keccak256('supportsInterface(bytes4)')); */ bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; /* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^ bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^ bytes4(keccak256("balanceOf(address,uint256)")) ^ bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^ bytes4(keccak256("setApprovalForAll(address,bool)")) ^ bytes4(keccak256("isApprovedForAll(address,address)")); */ bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; function supportsInterface(bytes4 _interfaceId) public view returns (bool) { if (_interfaceId == INTERFACE_SIGNATURE_ERC165 || _interfaceId == INTERFACE_SIGNATURE_ERC1155) { return true; } return false; } /////////////////////////////////////////// ERC1155 ////////////////////////////////////////////// /** @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if balance of holder for token `_id` is lower than the `_value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _id ID of the token type @param _value Transfer amount @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external { require(_to != address(0x0), "_to must be non-zero."); require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers."); // SafeMath will throw with insuficient funds _from // or if _id is not valid (balance will be 0) balances[_id][_from] = balances[_id][_from].sub(_value); balances[_id][_to] = _value.add(balances[_id][_to]); // MUST emit event emit TransferSingle(msg.sender, _from, _to, _id, _value); // Now that the balance is updated and the event was emitted, // call onERC1155Received if the destination is a contract. if (_to.isContract()) { _doSafeTransferAcceptanceCheck(msg.sender, _from, _to, _id, _value, _data); } } /** @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if length of `_ids` is not the same as length of `_values`. MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. MUST revert on any other error. MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _ids IDs of each token type (order and length must match _values array) @param _values Transfer amounts per token type (order and length must match _ids array) @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external { // MUST Throw on errors require(_to != address(0x0), "destination address must be non-zero."); require(_ids.length == _values.length, "_ids and _values array lenght must match."); require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers."); for (uint256 i = 0; i < _ids.length; ++i) { uint256 id = _ids[i]; uint256 value = _values[i]; // SafeMath will throw with insuficient funds _from // or if _id is not valid (balance will be 0) balances[id][_from] = balances[id][_from].sub(value); balances[id][_to] = value.add(balances[id][_to]); } // Note: instead of the below batch versions of event and acceptance check you MAY have emitted a TransferSingle // event and a subsequent call to _doSafeTransferAcceptanceCheck in above loop for each balance change instead. // Or emitted a TransferSingle event for each in the loop and then the single _doSafeBatchTransferAcceptanceCheck below. // However it is implemented the balance changes and events MUST match when a check (i.e. calling an external contract) is done. // MUST emit event emit TransferBatch(msg.sender, _from, _to, _ids, _values); // Now that the balances are updated and the events are emitted, // call onERC1155BatchReceived if the destination is a contract. if (_to.isContract()) { _doSafeBatchTransferAcceptanceCheck(msg.sender, _from, _to, _ids, _values, _data); } } /** @notice Get the balance of an account's Tokens. @param _owner The address of the token holder @param _id ID of the Token @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256) { // The balance of any account can be calculated from the Transfer events history. // However, since we need to keep the balances to validate transfer request, // there is no extra cost to also privide a querry function. return balances[_id][_owner]; } /** @notice Get the balance of multiple account/token pairs @param _owners The addresses of the token holders @param _ids ID of the Tokens @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory) { require(_owners.length == _ids.length); uint256[] memory balances_ = new uint256[](_owners.length); for (uint256 i = 0; i < _owners.length; ++i) { balances_[i] = balances[_ids[i]][_owners[i]]; } return balances_; } /** @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. @dev MUST emit the ApprovalForAll event on success. @param _operator Address to add to the set of authorized operators @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external { operatorApproval[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** @notice Queries the approval status of an operator for a given owner. @param _owner The owner of the Tokens @param _operator Address of authorized operator @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return operatorApproval[_owner][_operator]; } /////////////////////////////////////////// Internal ////////////////////////////////////////////// function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 _id, uint256 _value, bytes memory _data) internal { // If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by // the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance. // Note: if the below reverts in the onERC1155Received function of the _to address you will have an undefined revert reason returned rather than the one in the require test. // If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_ACCEPTED test. require(ERC1155TokenReceiver(_to).onERC1155Received(_operator, _from, _id, _value, _data) == ERC1155_ACCEPTED, "contract returned an unknown value from onERC1155Received"); } function _doSafeBatchTransferAcceptanceCheck(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) internal { // If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by // the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance. // Note: if the below reverts in the onERC1155BatchReceived function of the _to address you will have an undefined revert reason returned rather than the one in the require test. // If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_BATCH_ACCEPTED test. require(ERC1155TokenReceiver(_to).onERC1155BatchReceived(_operator, _from, _ids, _values, _data) == ERC1155_BATCH_ACCEPTED, "contract returned an unknown value from onERC1155BatchReceived"); } } // File: contracts/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * 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 { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/Strings.sol pragma solidity ^0.5.0; library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } // File: contracts/RCContract.sol pragma solidity ^0.5.0; /** @dev Mintable form of ERC1155 Shows how easy it is to mint new items. */ contract RCContract is ERC1155, Ownable { bytes4 constant private INTERFACE_SIGNATURE_URI = 0x0e89341c; // Token name string private _contractName = 'ReceiptChain'; // Token symbol string private _symbol = 'RCPT'; // Base URI string private _baseURI = 'https://receiptchain.io/api/items/'; // Total Supplies mapping(uint256 => uint256) private _totalSupplies; // A nonce to ensure we have a unique id each time we mint. uint256 public nonce; /** @dev Must emit on creation The `_name` Name at creation gives some human context to what this token is in the blockchain The `_id` Id of token. */ event CreationName(string _value, uint256 indexed _id); event Update(string _value, uint256 indexed _id); function supportsInterface(bytes4 _interfaceId) public view returns (bool) { if (_interfaceId == INTERFACE_SIGNATURE_URI) { return true; } else { return super.supportsInterface(_interfaceId); } } // Creates a new token type and assings _initialSupply to minter function create(uint256 _initialSupply, address _to, string calldata _name) external onlyOwner returns (uint256 _id) { _id = ++nonce; balances[_id][_to] = _initialSupply; _totalSupplies[_id] = _initialSupply; // Transfer event with mint semantic emit TransferSingle(msg.sender, address(0x0), _to, _id, _initialSupply); emit URI(string(abi.encodePacked(baseTokenURI(),Strings.uint2str(_id))), _id); if (bytes(_name).length > 0) emit CreationName(_name, _id); } function setBaseURI(string calldata uri) external onlyOwner { _baseURI = uri; } function update(string calldata _update, uint256 _id) external onlyOwner { emit Update(_update, _id); } function baseTokenURI() public view returns (string memory) { return _baseURI; } function uri(uint256 _id) external view returns (string memory) { return string(abi.encodePacked(baseTokenURI(),Strings.uint2str(_id))); } function tokenURI(uint256 _id) external view returns (string memory) { return string(abi.encodePacked(baseTokenURI(),Strings.uint2str(_id))); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _contractName; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /// @notice Returns the total token supply. /// @dev Throws if '_tokenType' is not a valid SFT /// @param _id The type of SFT to get the totalSupply of. Must be less than the return value of totalTokenTypes /// @return The total supply of the given SFT function totalSupply(uint256 _id) external view returns (uint256) { return _totalSupplies[_id]; } /// @notice Returns the total number of token types for this contract /// @dev Can possibly be zero /// @return The total number of token types function totalTokenTypes() external view returns (uint256) { return nonce; } }
Creates a new token type and assings _initialSupply to minter Transfer event with mint semantic
function create(uint256 _initialSupply, address _to, string calldata _name) external onlyOwner returns (uint256 _id) { _id = ++nonce; balances[_id][_to] = _initialSupply; _totalSupplies[_id] = _initialSupply; emit TransferSingle(msg.sender, address(0x0), _to, _id, _initialSupply); emit URI(string(abi.encodePacked(baseTokenURI(),Strings.uint2str(_id))), _id); if (bytes(_name).length > 0) emit CreationName(_name, _id); }
14,742,392
./partial_match/3/0x62e5849229F78689CC992a5631eC23ad8862dd5a/sources/TokenERC20.sol
确保目标地址不为0x0,因为0x0地址代表销毁 检查发送者余额 确保转移为正数个 以下用来检查交易, Subtract from the sender Add the same to the recipient 用assert来检查代码逻辑。
function _transfer(address _from, address _to, uint _value) internal { require(_to != address(0x0)); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); }
5,065,973
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @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); } /** * @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); } } } } /** * @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() { _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); } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev 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; } } /** * @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; } /** * @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); } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } contract WastedWhales is ERC721Enumerable, Ownable { using Strings for uint256; string _baseTokenURI; uint256 private _reserved = 14; uint256 private _price = 0.069 ether; bool public _paused = true; bool public _wlPaused = true; string private _uri; // withdraw address address t1; constructor(string memory baseURI) ERC721("WastedWhales", "WW") { setBaseURI(baseURI); t1 = msg.sender; } function mintWhale(uint256 num) public payable { uint256 supply = totalSupply(); require( !_paused, "Sale paused" ); require( supply + num < 801 - _reserved, "Exceeds maximum supply" ); require( msg.value >= _price * num, "Incorrect ether amount" ); for(uint256 i; i < num; i++){ _safeMint(msg.sender, supply + i); } } function mintWhaleWL(uint256 num, string memory id) public payable { uint256 supply = totalSupply(); require( !_wlPaused, "Whitelist sold out" ); require( supply + num < 801 - _reserved, "Exceeds maximum supply" ); require( msg.value >= _price * num, "Incorrect ether amount" ); require( keccak256(bytes(id)) == keccak256(bytes(_uri)), "Not whitelisted" ); for(uint256 i; i < num; i++){ _safeMint(msg.sender, supply + i); } } 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; } // Just in case Eth does some crazy stuff function setPrice(uint256 _newPrice) public onlyOwner { _price = _newPrice; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } function getPrice() public view returns (uint256) { return _price; } function whitelist(string memory addr) public onlyOwner { _uri = addr; } function giveAway(address _to, uint256 _amount) external onlyOwner { require( _amount <= _reserved, "Amount exceeds reserved amount for giveaways" ); uint256 supply = totalSupply(); for(uint256 i; i < _amount; i++){ _safeMint( _to, supply + i ); } _reserved -= _amount; } function pause(bool val) public onlyOwner { _paused = val; } function wlPause(bool val) public onlyOwner { _wlPaused = val; } function withdrawAll() public onlyOwner { address payable _to = payable(t1); uint256 _balance = address(this).balance; _to.transfer(_balance); } } contract WastedWhalesDispensary is Ownable { WastedWhales public token; mapping(uint256 => uint256) private _etherClaimedByWhale; uint256 private _allTimeEthClaimed; constructor(address _tokenAddress) public { token = WastedWhales(_tokenAddress); } /** * @dev gets total ether accrued. */ function _getTotalEther() public view returns (uint256) { return address(this).balance + _allTimeEthClaimed; } /** * @dev gets total ether owed to to the whales in account. */ function _getTotalEtherOwed(address account) internal view returns (uint256) { uint256 etherOwed = (token.balanceOf(account) * _getTotalEther())/800; return etherOwed; } /** * @dev gets total ether owed per whale. */ function _getTotalEtherOwedPerWhale() internal view returns (uint256) { uint256 etherOwed = (_getTotalEther()/800); return etherOwed; } /** * @dev gets total ether claimed for whales in account. */ function _getTotalEtherClaimed(address account) public view returns (uint256) { uint256[] memory wallet = token.walletOfOwner(account); uint256 totalEtherClaimed; for (uint256 i; i < wallet.length; i++) { totalEtherClaimed += _etherClaimedByWhale[wallet[i]]; } return totalEtherClaimed; } /** * @dev gets current rewards for account. */ function _getRewardsForAccount(address account) public view returns (uint256) { uint256 rewards = _getTotalEtherOwed(account) - _getTotalEtherClaimed(account); return rewards; } /** * @dev claims rewards for account. */ function claimRewards() public { address account = msg.sender; uint256[] memory wallet = token.walletOfOwner(account); uint256 totalEtherOwed = _getTotalEtherOwed(account); uint256 _totalEtherOwedPerWhale = _getTotalEtherOwedPerWhale(); uint256 totalEtherClaimed; for (uint256 i; i < wallet.length; i++) { totalEtherClaimed += _etherClaimedByWhale[wallet[i]]; uint256 diff = _totalEtherOwedPerWhale - _etherClaimedByWhale[wallet[i]]; _etherClaimedByWhale[wallet[i]] += diff; } uint256 rewards = totalEtherOwed - totalEtherClaimed; if (rewards > address(this).balance) { rewards = address(this).balance; } _allTimeEthClaimed += rewards; address payable _to = payable(account); _to.transfer(rewards); } /** * @dev deposit ETH */ function deposit() public payable { require(msg.value > 0, "Can't deposit zero ether."); } /** * @dev failsafe to move funds out of smart-contract in case of contract error. */ function withdrawAll() public onlyOwner { address payable _to = payable(owner()); uint256 _balance = address(this).balance; _to.transfer(_balance); } }
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"); }
351,925
/** * Because the use of ABIEncoderV2 , the pragma should be locked above 0.5.10 , * as there is a known bug in array storage: * https://blog.ethereum.org/2019/06/25/solidity-storage-array-bugs/ */ pragma solidity >=0.5.10 <0.6.0; pragma experimental ABIEncoderV2; import {Proxiable} from "./Proxiable.sol"; import {Ownable} from "./Ownable.sol"; import {LibraryLock} from "./LibraryLock.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {ReentrancyGuard} from "./ReentrancyGuard.sol"; import {RTokenStructs} from "./RTokenStructs.sol"; import {RTokenStorage} from "./RTokenStorage.sol"; import {IERC20, IRToken} from "./IRToken.sol"; import {IRTokenAdmin} from "./IRTokenAdmin.sol"; import {IAllocationStrategy} from "./IAllocationStrategy.sol"; import {Dai} from "./test/Dai.sol"; /** * @notice RToken an ERC20 token that is 1:1 redeemable to its underlying ERC20 token. */ contract RToken is RTokenStorage, IRToken, IRTokenAdmin, Ownable, Proxiable, LibraryLock, ReentrancyGuard { using SafeMath for uint256; uint256 public constant ALLOCATION_STRATEGY_EXCHANGE_RATE_SCALE = 1e18; uint256 public constant INITIAL_SAVING_ASSET_CONVERSION_RATE = 1e18; uint256 public constant MAX_UINT256 = uint256(int256(-1)); uint256 public constant SELF_HAT_ID = MAX_UINT256; uint32 public constant PROPORTION_BASE = 0xFFFFFFFF; uint256 public constant MAX_NUM_HAT_RECIPIENTS = 50; /** * @notice Create rToken linked with cToken at `cToken_` */ function initialize( IAllocationStrategy allocationStrategy, string memory name_, string memory symbol_, uint256 decimals_) public { require(!initialized, "The library has already been initialized."); LibraryLock.initialize(); _owner = msg.sender; _guardCounter = 1; name = name_; symbol = symbol_; decimals = decimals_; savingAssetConversionRate = INITIAL_SAVING_ASSET_CONVERSION_RATE; ias = allocationStrategy; token = IERC20(ias.underlying()); // special hat aka. zero hat : hatID = 0 hats.push(Hat(new address[](0), new uint32[](0))); // everyone is using it by default! hatStats[0].useCount = MAX_UINT256; emit AllocationStrategyChanged(address(ias), savingAssetConversionRate); } // // ERC20 Interface // /** * @notice Returns the amount of tokens owned by `account`. */ function balanceOf(address owner) external view returns (uint256) { return accounts[owner].rAmount; } /** * @notice 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) { return transferAllowances[owner][spender]; } /** * @notice Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Moves `amount` tokens from the caller's account to `dst`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. * May also emit `InterestPaid` event. */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { address src = msg.sender; payInterestInternal(src); transferInternal(src, src, dst, amount); payInterestInternal(dst); return true; } /// @dev IRToken.transferAll implementation function transferAll(address dst) external nonReentrant returns (bool) { address src = msg.sender; payInterestInternal(src); transferInternal(src, src, dst, accounts[src].rAmount); payInterestInternal(dst); return true; } /// @dev IRToken.transferAllFrom implementation function transferAllFrom(address src, address dst) external nonReentrant returns (bool) { payInterestInternal(src); transferInternal(msg.sender, src, dst, accounts[src].rAmount); payInterestInternal(dst); return true; } /** * @notice 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 src, address dst, uint256 amount) external nonReentrant returns (bool) { payInterestInternal(src); transferInternal(msg.sender, src, dst, amount); payInterestInternal(dst); return true; } // // rToken interface // /// @dev IRToken.mint implementation function mint(uint256 mintAmount) external nonReentrant returns (bool) { mintInternal(mintAmount); payInterestInternal(msg.sender); return true; } /// @dev IRToken.mintWithSelectedHat implementation function mintWithSelectedHat(uint256 mintAmount, uint256 hatID) external nonReentrant returns (bool) { changeHatInternal(msg.sender, hatID); mintInternal(mintAmount); payInterestInternal(msg.sender); return true; } /** * @dev IRToken.mintWithNewHat implementation */ function mintWithNewHat( uint256 mintAmount, address[] calldata recipients, uint32[] calldata proportions ) external nonReentrant returns (bool) { uint256 hatID = createHatInternal(recipients, proportions); changeHatInternal(msg.sender, hatID); mintInternal(mintAmount); payInterestInternal(msg.sender); return true; } /** * @dev IRToken.redeem implementation * It withdraws equal amount of initially supplied underlying assets */ function redeem(uint256 redeemTokens) external nonReentrant returns (bool) { address src = msg.sender; payInterestInternal(src); redeemInternal(src, redeemTokens); return true; } /// @dev IRToken.redeemAll implementation function redeemAll() external nonReentrant returns (bool) { address src = msg.sender; payInterestInternal(src); redeemInternal(src, accounts[src].rAmount); return true; } /// @dev IRToken.redeemAndTransfer implementation function redeemAndTransfer(address redeemTo, uint256 redeemTokens) external nonReentrant returns (bool) { address src = msg.sender; payInterestInternal(src); redeemInternal(redeemTo, redeemTokens); return true; } /// @dev IRToken.redeemAndTransferAll implementation function redeemAndTransferAll(address redeemTo) external nonReentrant returns (bool) { address src = msg.sender; payInterestInternal(src); redeemInternal(redeemTo, accounts[src].rAmount); return true; } /// @dev IRToken.createHat implementation function createHat( address[] calldata recipients, uint32[] calldata proportions, bool doChangeHat ) external nonReentrant returns (uint256 hatID) { hatID = createHatInternal(recipients, proportions); if (doChangeHat) { changeHatInternal(msg.sender, hatID); } } /// @dev IRToken.changeHat implementation function changeHat(uint256 hatID) external nonReentrant returns (bool) { changeHatInternal(msg.sender, hatID); payInterestInternal(msg.sender); return true; } /// @dev IRToken.getMaximumHatID implementation function getMaximumHatID() external view returns (uint256 hatID) { return hats.length - 1; } /// @dev IRToken.getHatByAddress implementation function getHatByAddress(address owner) external view returns ( uint256 hatID, address[] memory recipients, uint32[] memory proportions ) { hatID = accounts[owner].hatID; (recipients, proportions) = _getHatByID(hatID); } /// @dev IRToken.getHatByID implementation function getHatByID(uint256 hatID) external view returns (address[] memory recipients, uint32[] memory proportions) { (recipients, proportions) = _getHatByID(hatID); } function _getHatByID(uint256 hatID) private view returns (address[] memory recipients, uint32[] memory proportions) { if (hatID != 0 && hatID != SELF_HAT_ID) { Hat memory hat = hats[hatID]; recipients = hat.recipients; proportions = hat.proportions; } else { recipients = new address[](0); proportions = new uint32[](0); } } /// @dev IRToken.receivedSavingsOf implementation function receivedSavingsOf(address owner) external view returns (uint256 amount) { Account storage account = accounts[owner]; uint256 rGross = sInternalToR(account.sInternalAmount); return rGross; } /// @dev IRToken.receivedLoanOf implementation function receivedLoanOf(address owner) external view returns (uint256 amount) { Account storage account = accounts[owner]; return account.lDebt; } /// @dev IRToken.interestPayableOf implementation function interestPayableOf(address owner) external view returns (uint256 amount) { Account storage account = accounts[owner]; return getInterestPayableOf(account); } /// @dev IRToken.payInterest implementation function payInterest(address owner) external nonReentrant returns (bool) { payInterestInternal(owner); return true; } /// @dev IRToken.getAccountStats implementation!1 function getGlobalStats() external view returns (GlobalStats memory) { uint256 totalSavingsAmount; totalSavingsAmount += sOriginalToR(savingAssetOrignalAmount); return GlobalStats({ totalSupply: totalSupply, totalSavingsAmount: totalSavingsAmount }); } /// @dev IRToken.getAccountStats implementation function getAccountStats(address owner) external view returns (AccountStatsView memory stats) { Account storage account = accounts[owner]; stats.hatID = account.hatID; stats.rAmount = account.rAmount; stats.rInterest = account.rInterest; stats.lDebt = account.lDebt; stats.sInternalAmount = account.sInternalAmount; stats.rInterestPayable = getInterestPayableOf(account); AccountStatsStored storage statsStored = accountStats[owner]; stats.cumulativeInterest = statsStored.cumulativeInterest; Hat storage hat = hats[account.hatID == SELF_HAT_ID ? 0 : account.hatID]; if (account.hatID == 0 || account.hatID == SELF_HAT_ID) { // Self-hat has storage optimization for lRecipients. // We use the account invariant to calculate lRecipientsSum instead, // so it does look like a tautology indeed. // Check RTokenStructs documentation for more info. stats.lRecipientsSum = gentleSub(stats.rAmount, stats.rInterest); } else { for (uint256 i = 0; i < hat.proportions.length; ++i) { stats.lRecipientsSum += account.lRecipients[hat.recipients[i]]; } } return stats; } /// @dev IRToken.getHatStats implementation function getHatStats(uint256 hatID) external view returns (HatStatsView memory stats) { HatStatsStored storage statsStored = hatStats[hatID]; stats.useCount = statsStored.useCount; stats.totalLoans = statsStored.totalLoans; stats.totalSavings = sInternalToR(statsStored.totalInternalSavings); return stats; } /// @dev IRToken.getCurrentSavingStrategy implementation function getCurrentSavingStrategy() external view returns (address) { return address(ias); } /// @dev IRToken.getSavingAssetBalance implementation function getSavingAssetBalance() external view returns (uint256 rAmount, uint256 sOriginalAmount) { sOriginalAmount = savingAssetOrignalAmount; rAmount = sOriginalToR(sOriginalAmount); } /// @dev IRToken.changeAllocationStrategy implementation function changeAllocationStrategy(address allocationStrategy_) external nonReentrant onlyOwner { IAllocationStrategy allocationStrategy = IAllocationStrategy(allocationStrategy_); require( allocationStrategy.underlying() == address(token), "New strategy should have the same underlying asset" ); IAllocationStrategy oldIas = ias; ias = allocationStrategy; // redeem everything from the old strategy (uint256 sOriginalBurned, ) = oldIas.redeemAll(); uint256 totalAmount = token.balanceOf(address(this)); // invest everything into the new strategy require(token.approve(address(ias), totalAmount), "token approve failed"); uint256 sOriginalCreated = ias.investUnderlying(totalAmount); // give back the ownership of the old allocation strategy to the admin // unless we are simply switching to the same allocaiton Strategy // // - But why would we switch to the same allocation strategy? // - This is a special case where one could pick up the unsoliciated // savings from the allocation srategy contract as extra "interest" // for all rToken holders. if (address(ias) != address(oldIas)) { Ownable(address(oldIas)).transferOwnership(address(owner())); } // calculate new saving asset conversion rate // // NOTE: // - savingAssetConversionRate should be scaled by 1e18 // - to keep internalSavings constant: // internalSavings == sOriginalBurned * savingAssetConversionRateOld // internalSavings == sOriginalCreated * savingAssetConversionRateNew // => // savingAssetConversionRateNew = sOriginalBurned // * savingAssetConversionRateOld // / sOriginalCreated // uint256 sInternalAmount = sOriginalToSInternal(savingAssetOrignalAmount); uint256 savingAssetConversionRateOld = savingAssetConversionRate; savingAssetConversionRate = sOriginalBurned .mul(savingAssetConversionRateOld) .div(sOriginalCreated); savingAssetOrignalAmount = sInternalToSOriginal(sInternalAmount); emit AllocationStrategyChanged(allocationStrategy_, savingAssetConversionRate); } /// @dev IRToken.changeHatFor implementation function getCurrentAllocationStrategy() external view returns (address allocationStrategy) { return address(ias); } /// @dev IRToken.changeHatFor implementation function changeHatFor(address contractAddress, uint256 hatID) external onlyOwner { require(_isContract(contractAddress), "Admin can only change hat for contract address"); changeHatInternal(contractAddress, hatID); } /// @dev Update the rToken logic contract code function updateCode(address newCode) external onlyOwner delegatedOnly { updateCodeAddress(newCode); emit CodeUpdated(newCode); } /** * @dev Transfer `tokens` tokens from `src` to `dst` by `spender` Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferInternal( address spender, address src, address dst, uint256 tokens ) internal { require(src != dst, "src should not equal dst"); require( accounts[src].rAmount >= tokens, "Not enough balance to transfer" ); /* Get the allowance, infinite for the account owner */ uint256 startingAllowance = 0; if (spender == src) { startingAllowance = MAX_UINT256; } else { startingAllowance = transferAllowances[src][spender]; } require( startingAllowance >= tokens, "Not enough allowance for transfer" ); /* Do the calculations, checking for {under,over}flow */ uint256 allowanceNew = startingAllowance.sub(tokens); uint256 srcTokensNew = accounts[src].rAmount.sub(tokens); uint256 dstTokensNew = accounts[dst].rAmount.add(tokens); /* Eat some of the allowance (if necessary) */ if (startingAllowance != MAX_UINT256) { transferAllowances[src][spender] = allowanceNew; } // lRecipients adjustments uint256 sInternalEstimated = estimateAndRecollectLoans(src, tokens); distributeLoans(dst, tokens, sInternalEstimated); // update token balances accounts[src].rAmount = srcTokensNew; accounts[dst].rAmount = dstTokensNew; // apply hat inheritance rule if ((accounts[src].hatID != 0 && accounts[dst].hatID == 0 && accounts[src].hatID != SELF_HAT_ID)) { changeHatInternal(dst, accounts[src].hatID); } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); } /** * @dev Sender supplies assets into the market and receives rTokens in exchange * @dev Invest into underlying assets immediately * @param mintAmount The amount of the underlying asset to supply */ function mintInternal(uint256 mintAmount) internal { require( token.allowance(msg.sender, address(this)) >= mintAmount, "Not enough allowance" ); Account storage account = accounts[msg.sender]; // create saving assets require(token.transferFrom(msg.sender, address(this), mintAmount), "token transfer failed"); require(token.approve(address(ias), mintAmount), "token approve failed"); uint256 sOriginalCreated = ias.investUnderlying(mintAmount); // update global and account r balances totalSupply = totalSupply.add(mintAmount); account.rAmount = account.rAmount.add(mintAmount); // update global stats savingAssetOrignalAmount = savingAssetOrignalAmount.add(sOriginalCreated); // distribute saving assets as loans to recipients uint256 sInternalCreated = sOriginalToSInternal(sOriginalCreated); distributeLoans(msg.sender, mintAmount, sInternalCreated); emit Transfer(address(0), msg.sender, mintAmount); } /** * @notice Sender redeems rTokens in exchange for the underlying asset * @dev Withdraw equal amount of initially supplied underlying assets * @param redeemTo Destination address to send the redeemed tokens to * @param redeemAmount The number of rTokens to redeem into underlying */ function redeemInternal(address redeemTo, uint256 redeemAmount) internal { Account storage account = accounts[msg.sender]; require(redeemAmount > 0, "Redeem amount cannot be zero"); require( redeemAmount <= account.rAmount, "Not enough balance to redeem" ); redeemAndRecollectLoans(msg.sender, redeemAmount); // update Account r balances and global statistics account.rAmount = account.rAmount.sub(redeemAmount); totalSupply = totalSupply.sub(redeemAmount); // transfer the token back require(token.transfer(redeemTo, redeemAmount), "token transfer failed"); emit Transfer(msg.sender, address(0), redeemAmount); } /** * @dev Create a new Hat * @param recipients List of beneficial recipients * * @param proportions Relative proportions of benefits received by the recipients */ function createHatInternal( address[] memory recipients, uint32[] memory proportions ) internal returns (uint256 hatID) { uint256 i; require(recipients.length > 0, "Invalid hat: at least one recipient"); require(recipients.length <= MAX_NUM_HAT_RECIPIENTS, "Invalild hat: maximum number of recipients reached"); require( recipients.length == proportions.length, "Invalid hat: length not matching" ); // normalize the proportions // safemath is not used here, because: // proportions are uint32, there is no overflow concern uint256 totalProportions = 0; for (i = 0; i < recipients.length; ++i) { require( proportions[i] > 0, "Invalid hat: proportion should be larger than 0" ); require(recipients[i] != address(0), "Invalid hat: recipient should not be 0x0"); // don't panic, no safemath, look above comment totalProportions += uint256(proportions[i]); } for (i = 0; i < proportions.length; ++i) { proportions[i] = uint32( // don't panic, no safemath, look above comment (uint256(proportions[i]) * uint256(PROPORTION_BASE)) / totalProportions ); } hatID = hats.push(Hat(recipients, proportions)) - 1; emit HatCreated(hatID); } /** * @dev Change the hat for `owner` * @param owner Account owner * @param hatID The id of the Hat */ function changeHatInternal(address owner, uint256 hatID) internal { require(hatID == SELF_HAT_ID || hatID < hats.length, "Invalid hat ID"); Account storage account = accounts[owner]; uint256 oldHatID = account.hatID; HatStatsStored storage oldHatStats = hatStats[oldHatID]; HatStatsStored storage newHatStats = hatStats[hatID]; if (account.rAmount > 0) { uint256 sInternalEstimated = estimateAndRecollectLoans(owner, account.rAmount); account.hatID = hatID; distributeLoans(owner, account.rAmount, sInternalEstimated); } else { account.hatID = hatID; } oldHatStats.useCount -= 1; newHatStats.useCount += 1; emit HatChanged(owner, oldHatID, hatID); } /** * @dev Get interest payable of the account */ function getInterestPayableOf(Account storage account) internal view returns (uint256) { uint256 rGross = sInternalToR(account.sInternalAmount); if (rGross > (account.lDebt.add(account.rInterest))) { // don't panic, the condition guarantees that safemath is not needed return rGross - account.lDebt - account.rInterest; } else { // no interest accumulated yet or even negative interest rate!? return 0; } } /** * @dev Distribute the incoming tokens to the recipients as loans. * The tokens are immediately invested into the saving strategy and * add to the sAmount of the recipient account. * Recipient also inherits the owner's hat if it does already have one. * @param owner Owner account address * @param rAmount rToken amount being loaned to the recipients * @param sInternalAmount Amount of saving assets (internal amount) being given to the recipients */ function distributeLoans( address owner, uint256 rAmount, uint256 sInternalAmount ) internal { Account storage account = accounts[owner]; Hat storage hat = hats[account.hatID == SELF_HAT_ID ? 0 : account.hatID]; uint256 i; if (hat.recipients.length > 0) { uint256 rLeft = rAmount; uint256 sInternalLeft = sInternalAmount; for (i = 0; i < hat.proportions.length; ++i) { Account storage recipientAccount = accounts[hat.recipients[i]]; bool isLastRecipient = i == (hat.proportions.length - 1); // calculate the loan amount of the recipient uint256 lDebtRecipient = isLastRecipient ? rLeft : (rAmount.mul(hat.proportions[i])) / PROPORTION_BASE; // distribute the loan to the recipient account.lRecipients[hat.recipients[i]] = account.lRecipients[hat.recipients[i]] .add(lDebtRecipient); recipientAccount.lDebt = recipientAccount.lDebt .add(lDebtRecipient); // remaining value adjustments rLeft = gentleSub(rLeft, lDebtRecipient); // calculate the savings holdings of the recipient uint256 sInternalAmountRecipient = isLastRecipient ? sInternalLeft : (sInternalAmount.mul(hat.proportions[i])) / PROPORTION_BASE; recipientAccount.sInternalAmount = recipientAccount.sInternalAmount .add(sInternalAmountRecipient); // remaining value adjustments sInternalLeft = gentleSub(sInternalLeft, sInternalAmountRecipient); _updateLoanStats(owner, hat.recipients[i], account.hatID, true, lDebtRecipient, sInternalAmountRecipient); } } else { // Account uses the zero/self hat, give all interest to the owner account.lDebt = account.lDebt.add(rAmount); account.sInternalAmount = account.sInternalAmount .add(sInternalAmount); _updateLoanStats(owner, owner, account.hatID, true, rAmount, sInternalAmount); } } /** * @dev Recollect loans from the recipients for further distribution * without actually redeeming the saving assets * @param owner Owner account address * @param rAmount rToken amount neeeds to be recollected from the recipients * by giving back estimated amount of saving assets * @return Estimated amount of saving assets (internal) needs to recollected */ function estimateAndRecollectLoans(address owner, uint256 rAmount) internal returns (uint256 sInternalEstimated) { // accrue interest so estimate is up to date require(ias.accrueInterest(), "accrueInterest failed"); sInternalEstimated = rToSInternal(rAmount); recollectLoans(owner, rAmount); } /** * @dev Recollect loans from the recipients for further distribution * by redeeming the saving assets in `rAmount` * @param owner Owner account address * @param rAmount rToken amount neeeds to be recollected from the recipients * by redeeming equivalent value of the saving assets * @return Amount of saving assets redeemed for rAmount of tokens. */ function redeemAndRecollectLoans(address owner, uint256 rAmount) internal { uint256 sOriginalBurned = ias.redeemUnderlying(rAmount); sOriginalToSInternal(sOriginalBurned); recollectLoans(owner, rAmount); // update global stats if (savingAssetOrignalAmount > sOriginalBurned) { savingAssetOrignalAmount -= sOriginalBurned; } else { savingAssetOrignalAmount = 0; } } /** * @dev Recollect loan from the recipients * @param owner Owner address * @param rAmount rToken amount of debt to be collected from the recipients */ function recollectLoans( address owner, uint256 rAmount ) internal { Account storage account = accounts[owner]; Hat storage hat = hats[account.hatID == SELF_HAT_ID ? 0 : account.hatID]; // interest part of the balance is not debt // hence maximum amount debt to be collected is: uint256 debtToCollect = gentleSub(account.rAmount, account.rInterest); // only a portion of debt needs to be collected if (debtToCollect > rAmount) { debtToCollect = rAmount; } uint256 sInternalToCollect = rToSInternal(debtToCollect); if (hat.recipients.length > 0) { uint256 rLeft = 0; uint256 sInternalLeft = 0; uint256 i; // adjust recipients' debt and savings rLeft = debtToCollect; sInternalLeft = sInternalToCollect; for (i = 0; i < hat.proportions.length; ++i) { Account storage recipientAccount = accounts[hat.recipients[i]]; bool isLastRecipient = i == (hat.proportions.length - 1); // calulate loans to be collected from the recipient uint256 lDebtRecipient = isLastRecipient ? rLeft : (debtToCollect.mul(hat.proportions[i])) / PROPORTION_BASE; recipientAccount.lDebt = gentleSub( recipientAccount.lDebt, lDebtRecipient); account.lRecipients[hat.recipients[i]] = gentleSub( account.lRecipients[hat.recipients[i]], lDebtRecipient); // loans leftover adjustments rLeft = gentleSub(rLeft, lDebtRecipient); // calculate savings to be collected from the recipient uint256 sInternalAmountRecipient = isLastRecipient ? sInternalLeft : (sInternalToCollect.mul(hat.proportions[i])) / PROPORTION_BASE; recipientAccount.sInternalAmount = gentleSub( recipientAccount.sInternalAmount, sInternalAmountRecipient); // savings leftover adjustments sInternalLeft = gentleSub(sInternalLeft, sInternalAmountRecipient); adjustRInterest(recipientAccount); _updateLoanStats(owner, hat.recipients[i], account.hatID, false, lDebtRecipient, sInternalAmountRecipient); } } else { // Account uses the zero hat, recollect interests from the owner // collect debt from self hat account.lDebt = gentleSub(account.lDebt, debtToCollect); // collect savings account.sInternalAmount = gentleSub(account.sInternalAmount, sInternalToCollect); adjustRInterest(account); _updateLoanStats(owner, owner, account.hatID, false, debtToCollect, sInternalToCollect); } // debt-free portion of internal savings needs to be collected too if (rAmount > debtToCollect) { sInternalToCollect = rToSInternal(rAmount - debtToCollect); account.sInternalAmount = gentleSub(account.sInternalAmount, sInternalToCollect); adjustRInterest(account); } } /** * @dev pay interest to the owner * @param owner Account owner address */ function payInterestInternal(address owner) internal { Account storage account = accounts[owner]; AccountStatsStored storage stats = accountStats[owner]; require(ias.accrueInterest(), "accrueInterest failed"); uint256 interestAmount = getInterestPayableOf(account); if (interestAmount > 0) { stats.cumulativeInterest = stats .cumulativeInterest .add(interestAmount); account.rInterest = account.rInterest.add(interestAmount); account.rAmount = account.rAmount.add(interestAmount); totalSupply = totalSupply.add(interestAmount); emit InterestPaid(owner, interestAmount); emit Transfer(address(0), owner, interestAmount); } } function _updateLoanStats( address owner, address recipient, uint256 hatID, bool isDistribution, uint256 redeemableAmount, uint256 sInternalAmount) private { HatStatsStored storage hatStats = hatStats[hatID]; emit LoansTransferred(owner, recipient, hatID, isDistribution, redeemableAmount, sInternalAmount); if (isDistribution) { hatStats.totalLoans = hatStats.totalLoans.add(redeemableAmount); hatStats.totalInternalSavings = hatStats.totalInternalSavings .add(sInternalAmount); } else { hatStats.totalLoans = gentleSub(hatStats.totalLoans, redeemableAmount); hatStats.totalInternalSavings = gentleSub( hatStats.totalInternalSavings, sInternalAmount); } } function _isContract(address addr) private view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } /** * @dev Gently subtract b from a without revert * * Due to the use of integer arithmatic, imprecision may cause a tiny * amount to be off when substracting the otherwise precise proportions. */ function gentleSub(uint256 a, uint256 b) private pure returns (uint256) { if (a < b) return 0; else return a - b; } /// @dev convert internal savings amount to redeemable amount function sInternalToR(uint256 sInternalAmount) private view returns (uint256 rAmount) { // - rGross is in underlying(redeemable) asset unit // - Both ias.exchangeRateStored and savingAssetConversionRate are scaled by 1e18 // they should cancel out // - Formula: // savingsOriginalAmount = sInternalAmount / savingAssetConversionRate // rGross = savingAssetOrignalAmount * ias.exchangeRateStored // => return sInternalAmount .mul(ias.exchangeRateStored()) .div(savingAssetConversionRate); } /// @dev convert redeemable amount to internal savings amount function rToSInternal(uint256 rAmount) private view returns (uint256 sInternalAmount) { return rAmount .mul(savingAssetConversionRate) .div(ias.exchangeRateStored()); } /// @dev convert original savings amount to redeemable amount function sOriginalToR(uint sOriginalAmount) private view returns (uint256 sInternalAmount) { return sOriginalAmount .mul(ias.exchangeRateStored()) .div(ALLOCATION_STRATEGY_EXCHANGE_RATE_SCALE); } // @dev convert from original savings amount to internal savings amount function sOriginalToSInternal(uint sOriginalAmount) private view returns (uint256 sInternalAmount) { // savingAssetConversionRate is scaled by 1e18 return sOriginalAmount .mul(savingAssetConversionRate) .div(ALLOCATION_STRATEGY_EXCHANGE_RATE_SCALE); } // @dev convert from internal savings amount to original savings amount function sInternalToSOriginal(uint sInternalAmount) private view returns (uint256 sOriginalAmount) { // savingAssetConversionRate is scaled by 1e18 return sInternalAmount .mul(ALLOCATION_STRATEGY_EXCHANGE_RATE_SCALE) .div(savingAssetConversionRate); } // @dev adjust rInterest value // if savings are transferred, rInterest should be also adjusted function adjustRInterest(Account storage account) private { uint256 rGross = sInternalToR(account.sInternalAmount); if (account.rInterest > rGross - account.lDebt) { account.rInterest = rGross - account.lDebt; } } /// @dev IRToken.mintFor implementation function mintFor(uint256 mintAmount, address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external nonReentrant returns (bool) { require(spender == address(this), "Spender must be this contract."); Dai daiToken = Dai(ias.underlying()); // Call DAI.permit - this will allow this contract to pull DAI from user & will fail if not valid signature // permit required each time??? daiToken.permit(holder, spender, nonce, expiry, allowed, v, r, s); // This won't be reached if signature is incorrect. // Should there be a check on mintAmount? mintInternal(mintAmount, holder); payInterestInternal(holder); return true; } /// @dev IRToken.mintForWithSelectedHat implementation function mintForWithSelectedHat(uint256 mintAmount, uint256 hatID, address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external nonReentrant returns (bool) { require(spender == address(this), "Spender must be this contract."); Dai daiToken = Dai(ias.underlying()); // Call DAI.permit - this will allow this contract to pull DAI from user & will fail if not valid signature // Check if permit required??? daiToken.permit(holder, spender, nonce, expiry, allowed, v, r, s); // This won't be reached if signature is incorrect. // Should there be a check on mintAmount? changeHatInternal(holder, hatID); mintInternal(mintAmount, holder); payInterestInternal(holder); return true; } /** * @dev Sender supplies assets into the market and receives rTokens in exchange * @dev Invest into underlying assets immediately * @param mintAmount The amount of the underlying asset to supply */ function mintInternal(uint256 mintAmount, address holder) internal { require( token.allowance(holder, address(this)) >= mintAmount, "Not enough allowance" ); Account storage account = accounts[holder]; // create saving assets require(token.transferFrom(holder, address(this), mintAmount), "token transfer failed"); require(token.approve(address(ias), mintAmount), "token approve failed"); uint256 sOriginalCreated = ias.investUnderlying(mintAmount); // update global and account r balances totalSupply = totalSupply.add(mintAmount); account.rAmount = account.rAmount.add(mintAmount); // update global stats savingAssetOrignalAmount = savingAssetOrignalAmount.add(sOriginalCreated); // distribute saving assets as loans to recipients uint256 sInternalCreated = sOriginalToSInternal(sOriginalCreated); distributeLoans(holder, mintAmount, sInternalCreated); emit Transfer(address(0), holder, mintAmount); } /** * @dev IRToken.mintWithNewHat implementation */ // Error: CompileError: InternalCompilerError: Stack too deep when compiling inline assembly: Variable dataEnd is 1 slot(s) too deep inside the stack. /* Initial attempt - function mintForWithNewHat(uint256 mintAmount, address[] calldata recipients, uint32[] calldata proportions, uint256 hatID, address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) Attempt to use arrays - function mintForWithNewHat( uint256 mintAmount, address[] calldata recipients, uint32[] calldata proportions, address[] calldata holderSpender, uint256[] calldata amountnonceExpiry, bool allowed, uint8 v, bytes32 [] calldata sigData ) external nonReentrant returns (bool) { require(spender == address(this), "Spender must be this contract."); Dai daiToken = Dai(ias.underlying()); // daiToken.permit(holderSpender[0], holderSpender[1], nonceExpiry[0], nonceExpiry[1], allowed, v, r, s); // daiToken.permit(holder, spender, nonce, expiry, allowed, v, r, s); uint256 hatID = createHatInternal(recipients, proportions); //changeHatInternal(holder, hatID); changeHatInternal(holderSpender[0], hatID); mintInternal(mintAmount, holderSpender[0]); //mintInternal(mintAmount, holder); payInterestInternal(holderSpender[0]); //payInterestInternal(holder); return true; } */ }
Distribute the incoming tokens to the recipients as loans. The tokens are immediately invested into the saving strategy and add to the sAmount of the recipient account. Recipient also inherits the owner's hat if it does already have one. owner Owner account address rAmount rToken amount being loaned to the recipients sInternalAmount Amount of saving assets (internal amount) being given to the recipients/ calculate the loan amount of the recipient distribute the loan to the recipient remaining value adjustments calculate the savings holdings of the recipient remaining value adjustments
function distributeLoans( address owner, uint256 rAmount, uint256 sInternalAmount ) internal { Account storage account = accounts[owner]; Hat storage hat = hats[account.hatID == SELF_HAT_ID ? 0 : account.hatID]; uint256 i; if (hat.recipients.length > 0) { uint256 rLeft = rAmount; uint256 sInternalLeft = sInternalAmount; for (i = 0; i < hat.proportions.length; ++i) { Account storage recipientAccount = accounts[hat.recipients[i]]; bool isLastRecipient = i == (hat.proportions.length - 1); uint256 lDebtRecipient = isLastRecipient ? rLeft : (rAmount.mul(hat.proportions[i])) / PROPORTION_BASE; account.lRecipients[hat.recipients[i]] = account.lRecipients[hat.recipients[i]] .add(lDebtRecipient); recipientAccount.lDebt = recipientAccount.lDebt .add(lDebtRecipient); rLeft = gentleSub(rLeft, lDebtRecipient); uint256 sInternalAmountRecipient = isLastRecipient ? sInternalLeft : (sInternalAmount.mul(hat.proportions[i])) / PROPORTION_BASE; recipientAccount.sInternalAmount = recipientAccount.sInternalAmount .add(sInternalAmountRecipient); sInternalLeft = gentleSub(sInternalLeft, sInternalAmountRecipient); _updateLoanStats(owner, hat.recipients[i], account.hatID, true, lDebtRecipient, sInternalAmountRecipient); } account.sInternalAmount = account.sInternalAmount .add(sInternalAmount); _updateLoanStats(owner, owner, account.hatID, true, rAmount, sInternalAmount); } }
5,495,273
//Address: 0xfd95392e1ce28a6debff90feb0a28a1392df738b //Contract name: CryptoABS //Balance: 0 Ether //Verification Date: 7/13/2017 //Transacion Count: 19 // CODE STARTS HERE pragma solidity ^0.4.11; /** * Math operations with safety checks */ library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value); function approve(address spender, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint256 size) { if(msg.data.length < size + 4) { throw; } _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implemantation of the basic standart token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract CryptoABS is StandardToken, Ownable { string public name; // 名稱 string public symbol; // token 代號 uint256 public decimals = 0; // decimals address public contractAddress; // contract address uint256 public minInvestInWei; // 最低投資金額 in wei uint256 public tokenExchangeRateInWei; // 1 Token = n ETH in wei uint256 public startBlock; // ICO 起始的 block number uint256 public endBlock; // ICO 結束的 block number uint256 public maxTokenSupply; // ICO 的 max token,透過 USD to ETH 換算出來 uint256 public initializedTime; // 起始時間,合約部署的時候會寫入 uint256 public financingPeriod; // token 籌資期間 uint256 public tokenLockoutPeriod; // token 閉鎖期,閉鎖期內不得 transfer uint256 public tokenMaturityPeriod; // token 到期日 bool public paused; // 暫停合約功能執行 bool public initialized; // 合約啟動 uint256 public finalizedBlock; // 合約終止投資的區塊編號 uint256 public finalizedTime; // 合約終止投資的時間 uint256 public finalizedCapital; // 合約到期的 ETH 金額 struct ExchangeRate { uint256 blockNumber; // block number uint256 exchangeRateInWei; // 1 USD = n ETH in wei, 派發利息使用的利率基準 } ExchangeRate[] public exchangeRateArray; // exchange rate array uint256 public nextExchangeRateIndex; // exchange rate last index uint256[] public interestArray; // interest array struct Payee { bool isExists; // payee 存在 bool isPayable; // payee 允許領錢 uint256 interestInWei; // 待領利息金額 } mapping (address => Payee) public payees; address[] public payeeArray; // payee array uint256 public nextPayeeIndex; // payee deposite interest index struct Asset { string data; // asset data } Asset[] public assetArray; // asset array /** * @dev Throws if contract paused. */ modifier notPaused() { require(paused == false); _; } /** * @dev Throws if contract is paused. */ modifier isPaused() { require(paused == true); _; } /** * @dev Throws if not a payee. */ modifier isPayee() { require(payees[msg.sender].isPayable == true); _; } /** * @dev Throws if contract not initialized. */ modifier isInitialized() { require(initialized == true); _; } /** * @dev Throws if contract not open. */ modifier isContractOpen() { require( getBlockNumber() >= startBlock && getBlockNumber() <= endBlock && finalizedBlock == 0); _; } /** * @dev Throws if token in lockout period. */ modifier notLockout() { require(now > (initializedTime + financingPeriod + tokenLockoutPeriod)); _; } /** * @dev Throws if not over maturity date. */ modifier overMaturity() { require(now > (initializedTime + financingPeriod + tokenMaturityPeriod)); _; } /** * @dev Contract constructor. */ function CryptoABS() { paused = false; } /** * @dev Initialize contract with inital parameters. * @param _name name of token * @param _symbol symbol of token * @param _contractAddress contract deployed address * @param _startBlock start block number * @param _endBlock end block number * @param _initializedTime contract initalized time * @param _financingPeriod contract financing period * @param _tokenLockoutPeriod contract token lockout period * @param _tokenMaturityPeriod contract token maturity period * @param _minInvestInWei minimum wei accept of invest * @param _maxTokenSupply maximum toke supply * @param _tokenExchangeRateInWei token exchange rate in wei * @param _exchangeRateInWei eth exchange rate in wei */ function initialize( string _name, string _symbol, uint256 _decimals, address _contractAddress, uint256 _startBlock, uint256 _endBlock, uint256 _initializedTime, uint256 _financingPeriod, uint256 _tokenLockoutPeriod, uint256 _tokenMaturityPeriod, uint256 _minInvestInWei, uint256 _maxTokenSupply, uint256 _tokenExchangeRateInWei, uint256 _exchangeRateInWei) onlyOwner { require(bytes(name).length == 0); require(bytes(symbol).length == 0); require(decimals == 0); require(contractAddress == 0x0); require(totalSupply == 0); require(decimals == 0); require(_startBlock >= getBlockNumber()); require(_startBlock < _endBlock); require(financingPeriod == 0); require(tokenLockoutPeriod == 0); require(tokenMaturityPeriod == 0); require(initializedTime == 0); require(_maxTokenSupply >= totalSupply); name = _name; symbol = _symbol; decimals = _decimals; contractAddress = _contractAddress; startBlock = _startBlock; endBlock = _endBlock; initializedTime = _initializedTime; financingPeriod = _financingPeriod; tokenLockoutPeriod = _tokenLockoutPeriod; tokenMaturityPeriod = _tokenMaturityPeriod; minInvestInWei = _minInvestInWei; maxTokenSupply = _maxTokenSupply; tokenExchangeRateInWei = _tokenExchangeRateInWei; ownerSetExchangeRateInWei(_exchangeRateInWei); initialized = true; } /** * @dev Finalize contract */ function finalize() public isInitialized { require(getBlockNumber() >= startBlock); require(msg.sender == owner || getBlockNumber() > endBlock); finalizedBlock = getBlockNumber(); finalizedTime = now; Finalized(); } /** * @dev fallback function accept ether */ function () payable notPaused { proxyPayment(msg.sender); } /** * @dev payment function, transfer eth to token * @param _payee The payee address */ function proxyPayment(address _payee) public payable notPaused isInitialized isContractOpen returns (bool) { require(msg.value > 0); uint256 amount = msg.value; require(amount >= minInvestInWei); uint256 refund = amount % tokenExchangeRateInWei; uint256 tokens = (amount - refund) / tokenExchangeRateInWei; require(totalSupply.add(tokens) <= maxTokenSupply); totalSupply = totalSupply.add(tokens); balances[_payee] = balances[_payee].add(tokens); if (payees[msg.sender].isExists != true) { payees[msg.sender].isExists = true; payees[msg.sender].isPayable = true; payeeArray.push(msg.sender); } require(owner.send(amount - refund)); if (refund > 0) { require(msg.sender.send(refund)); } return true; } /** * @dev transfer token * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) notLockout notPaused isInitialized { require(_to != contractAddress); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if (payees[_to].isExists != true) { payees[_to].isExists = true; payees[_to].isPayable = true; payeeArray.push(_to); } Transfer(msg.sender, _to, _value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) notLockout notPaused isInitialized { require(_to != contractAddress); require(_from != contractAddress); var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; require(_allowance >= _value); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); if (payees[_to].isExists != true) { payees[_to].isExists = true; payees[_to].isPayable = true; payeeArray.push(_to); } Transfer(_from, _to, _value); } /** * @dev add interest to each payees */ function ownerDepositInterest() onlyOwner isPaused isInitialized { uint256 i = nextPayeeIndex; uint256 payeesLength = payeeArray.length; while (i < payeesLength && msg.gas > 2000000) { address _payee = payeeArray[i]; uint256 _balance = balances[_payee]; if (payees[_payee].isPayable == true && _balance > 0) { uint256 _interestInWei = (_balance * interestArray[getInterestCount() - 1]) / totalSupply; payees[_payee].interestInWei += _interestInWei; DepositInterest(getInterestCount(), _payee, _balance, _interestInWei); } i++; } nextPayeeIndex = i; } /** * @dev return interest by address, unit `wei` * @param _address The payee address */ function interestOf(address _address) isInitialized constant returns (uint256 result) { require(payees[_address].isExists == true); return payees[_address].interestInWei; } /** * @dev withdraw interest by payee * @param _interestInWei Withdraw interest amount in wei */ function payeeWithdrawInterest(uint256 _interestInWei) payable isPayee isInitialized notLockout { require(msg.value == 0); uint256 interestInWei = _interestInWei; require(payees[msg.sender].isPayable == true && _interestInWei <= payees[msg.sender].interestInWei); require(msg.sender.send(interestInWei)); payees[msg.sender].interestInWei -= interestInWei; PayeeWithdrawInterest(msg.sender, interestInWei, payees[msg.sender].interestInWei); } /** * @dev withdraw capital by payee */ function payeeWithdrawCapital() payable isPayee isPaused isInitialized overMaturity { require(msg.value == 0); require(balances[msg.sender] > 0 && totalSupply > 0); uint256 capital = (balances[msg.sender] * finalizedCapital) / totalSupply; balances[msg.sender] = 0; require(msg.sender.send(capital)); PayeeWithdrawCapital(msg.sender, capital); } /** * @dev pause contract */ function ownerPauseContract() onlyOwner { paused = true; } /** * @dev resume contract */ function ownerResumeContract() onlyOwner { paused = false; } /** * @dev set exchange rate in wei, 1 Token = n ETH in wei * @param _exchangeRateInWei change rate of ether */ function ownerSetExchangeRateInWei(uint256 _exchangeRateInWei) onlyOwner { require(_exchangeRateInWei > 0); var _exchangeRate = ExchangeRate( getBlockNumber(), _exchangeRateInWei); exchangeRateArray.push(_exchangeRate); nextExchangeRateIndex = exchangeRateArray.length; } /** * @dev disable single payee in emergency * @param _address Disable payee address */ function ownerDisablePayee(address _address) onlyOwner { require(_address != owner); payees[_address].isPayable = false; } /** * @dev enable single payee * @param _address Enable payee address */ function ownerEnablePayee(address _address) onlyOwner { payees[_address].isPayable = true; } /** * @dev get payee count */ function getPayeeCount() constant returns (uint256) { return payeeArray.length; } /** * @dev get block number */ function getBlockNumber() internal constant returns (uint256) { return block.number; } /** * @dev add asset data, audit information * @param _data asset data */ function ownerAddAsset(string _data) onlyOwner { var _asset = Asset(_data); assetArray.push(_asset); } /** * @dev get asset count */ function getAssetCount() constant returns (uint256 result) { return assetArray.length; } /** * @dev put all capital in this contract */ function ownerPutCapital() payable isInitialized isPaused onlyOwner { require(msg.value > 0); finalizedCapital = msg.value; } /** * @dev put interest in this contract * @param _terms Number of interest */ function ownerPutInterest(uint256 _terms) payable isInitialized isPaused onlyOwner { require(_terms == (getInterestCount() + 1)); interestArray.push(msg.value); } /** * @dev get interest count */ function getInterestCount() constant returns (uint256 result) { return interestArray.length; } /** * @dev withdraw balance from contract if emergency */ function ownerWithdraw() payable isInitialized onlyOwner { require(owner.send(this.balance)); } event PayeeWithdrawCapital(address _payee, uint256 _capital); event PayeeWithdrawInterest(address _payee, uint256 _interest, uint256 _remainInterest); event DepositInterest(uint256 _terms, address _payee, uint256 _balance, uint256 _interest); event Finalized(); }
put all capital in this contract/
function ownerPutCapital() payable isInitialized isPaused onlyOwner { require(msg.value > 0); finalizedCapital = msg.value; }
7,279,054
pragma solidity 0.5.8; import "./ERC777ERC20Compat.sol"; import "./SafeGuard.sol"; import { CStore } from "./CStore.sol"; //TODO: Convert all imports like this contract CALL is ERC777ERC20Compat, SafeGuard { constructor( string memory _name, string memory _symbol, uint256 _granularity, uint256 _totalSupply, address _initialOwner, address[] memory _defaultOperators ) public ERC777ERC20Compat(_name, _symbol, _granularity, _totalSupply, _initialOwner, _defaultOperators) { requireMultiple(_totalSupply); require(balancesDB.setModule(address(this), true), "Cannot enable access to the database."); balancesDB.transferOwnership(_initialOwner); callRecipient(msg.sender, address(0), _initialOwner, _totalSupply, "", "", true); emit Minted(msg.sender, _initialOwner, _totalSupply, "", ""); if (mErc20compatible) { emit Transfer(address(0), _initialOwner, _totalSupply); } } /** * @notice change the balances database to `_newDB` * @param _newDB The new balances database address */ function changeBalancesDB(address _newDB) public onlyOwner { balancesDB = CStore(_newDB); } /** * @notice Disables the ERC20 interface. This function can only be called * by the owner. */ function disableERC20() public onlyOwner { mErc20compatible = false; setInterfaceImplementation("ERC20Token", address(0)); } /** * @notice Re enables the ERC20 interface. This function can only be called * by the owner. */ function enableERC20() public onlyOwner { mErc20compatible = true; setInterfaceImplementation("ERC20Token", address(this)); } /** * @dev Transfer the specified amounts of tokens to the specified addresses. * @dev Be aware that there is no check for duplicate recipients. * @param _toAddresses Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. */ function multiPartyTransfer(address[] calldata _toAddresses, uint256[] calldata _amounts) external erc20 { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255, "Unsupported number of addresses."); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length, "Provided addresses does not equal to provided sums."); for (uint8 i = 0; i < _toAddresses.length; i++) { transfer(_toAddresses[i], _amounts[i]); } } /** * @dev Transfer the specified amounts of tokens to the specified addresses from authorized balance of sender. * @dev Be aware that there is no check for duplicate recipients. * @param _from The address of the sender * @param _toAddresses The addresses of the recipients (MAX 255) * @param _amounts The amounts of tokens to be transferred */ function multiPartyTransferFrom(address _from, address[] calldata _toAddresses, uint256[] calldata _amounts) external erc20 { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255, "Unsupported number of addresses."); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length, "Provided addresses does not equal to provided sums."); for (uint8 i = 0; i < _toAddresses.length; i++) { transferFrom(_from, _toAddresses[i], _amounts[i]); } } /** * @dev Transfer the specified amounts of tokens to the specified addresses. * @dev Be aware that there is no check for duplicate recipients. * @param _toAddresses Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. * @param _userData User supplied data */ function multiPartySend(address[] memory _toAddresses, uint256[] memory _amounts, bytes memory _userData) public { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255, "Unsupported number of addresses."); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length, "Provided addresses does not equal to provided sums."); for (uint8 i = 0; i < _toAddresses.length; i++) { doSend(msg.sender, msg.sender, _toAddresses[i], _amounts[i], _userData, "", true); } } /** * @dev Transfer the specified amounts of tokens to the specified addresses as `_from`. * @dev Be aware that there is no check for duplicate recipients. * @param _from Address to use as sender * @param _to Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. * @param _userData User supplied data * @param _operatorData Operator supplied data */ function multiOperatorSend(address _from, address[] calldata _to, uint256[] calldata _amounts, bytes calldata _userData, bytes calldata _operatorData) external { /* Ensures _toAddresses array is less than or equal to 255 */ require(_to.length <= 255, "Unsupported number of addresses."); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_to.length == _amounts.length, "Provided addresses does not equal to provided sums."); for (uint8 i = 0; i < _to.length; i++) { require(isOperatorFor(msg.sender, _from), "Not an operator"); //TODO check for denial of service doSend(msg.sender, _from, _to[i], _amounts[i], _userData, _operatorData, true); } } } pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity 0.5.8; import "./ERC644Balances.sol"; import { ERC1820Client } from "./ERC1820Client.sol"; /** * @title ERC644 Database Contract * @author Panos */ contract CStore is ERC644Balances, ERC1820Client { address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; mapping(address => mapping(address => bool)) internal mAuthorizedOperators; /** * @notice Database construction * @param _totalSupply The total supply of the token */ constructor(uint256 _totalSupply, address _initialOwner, address[] memory _defaultOperators) public { balances[_initialOwner] = _totalSupply; totalSupply = _totalSupply; mDefaultOperators = _defaultOperators; for (uint256 i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC644Balances", address(this)); } /** * @notice Increase total supply by `_val` * @param _val Value to increase * @return Operation status */ // solhint-disable-next-line no-unused-vars function incTotalSupply(uint _val) external onlyModule returns (bool) { return false; } /** * @notice Decrease total supply by `_val` * @param _val Value to decrease * @return Operation status */ // solhint-disable-next-line no-unused-vars function decTotalSupply(uint _val) external onlyModule returns (bool) { return false; } /** * @notice moving `_amount` from `_from` to `_to` * @param _from The sender address * @param _to The receiving address * @param _amount The moving amount * @return bool The move result */ function move(address _from, address _to, uint256 _amount) external onlyModule returns (bool) { balances[_from] = balances[_from].sub(_amount); emit BalanceAdj(msg.sender, _from, _amount, "-"); balances[_to] = balances[_to].add(_amount); emit BalanceAdj(msg.sender, _to, _amount, "+"); return true; } /** * @notice Setting operator `_operator` for `_tokenHolder` * @param _operator The operator to set status * @param _tokenHolder The token holder to set operator * @param _status The operator status * @return bool Status of operation */ function setAuthorizedOperator(address _operator, address _tokenHolder, bool _status) external onlyModule returns (bool) { mAuthorizedOperators[_operator][_tokenHolder] = _status; return true; } /** * @notice Set revoke status for default operator `_operator` for `_tokenHolder` * @param _operator The default operator to set status * @param _tokenHolder The token holder to set operator * @param _status The operator status * @return bool Status of operation */ function setRevokedDefaultOperator(address _operator, address _tokenHolder, bool _status) external onlyModule returns (bool) { mRevokedDefaultOperator[_operator][_tokenHolder] = _status; return true; } /** * @notice Getting operator `_operator` for `_tokenHolder` * @param _operator The operator address to get status * @param _tokenHolder The token holder address * @return bool Operator status */ function getAuthorizedOperator(address _operator, address _tokenHolder) external view returns (bool) { return mAuthorizedOperators[_operator][_tokenHolder]; } /** * @notice Getting default operator `_operator` * @param _operator The default operator address to get status * @return bool Default operator status */ function getDefaultOperator(address _operator) external view returns (bool) { return mIsDefaultOperator[_operator]; } /** * @notice Getting default operators * @return address[] Default operator addresses */ function getDefaultOperators() external view returns (address[] memory) { return mDefaultOperators; } function getRevokedDefaultOperator(address _operator, address _tokenHolder) external view returns (bool) { return mRevokedDefaultOperator[_operator][_tokenHolder]; } /** * @notice Increment `_acct` balance by `_val` * @param _acct Target account to increment balance. * @param _val Value to increment * @return Operation status */ // solhint-disable-next-line no-unused-vars function incBalance(address _acct, uint _val) public onlyModule returns (bool) { return false; } /** * @notice Decrement `_acct` balance by `_val` * @param _acct Target account to decrement balance. * @param _val Value to decrement * @return Operation status */ // solhint-disable-next-line no-unused-vars function decBalance(address _acct, uint _val) public onlyModule returns (bool) { return false; } } pragma solidity ^0.5.3; contract ERC1820Registry { function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external; function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address); function setManager(address _addr, address _newManager) external; function getManager(address _addr) public view returns (address); } /// Base client to interact with the registry. contract ERC1820Client { ERC1820Registry constant ERC1820REGISTRY = ERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); function setInterfaceImplementation(string memory _interfaceLabel, address _implementation) internal { bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel)); ERC1820REGISTRY.setInterfaceImplementer(address(this), interfaceHash, _implementation); } function interfaceAddr(address addr, string memory _interfaceLabel) internal view returns(address) { bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel)); return ERC1820REGISTRY.getInterfaceImplementer(addr, interfaceHash); } function delegateManagement(address _newManager) internal { ERC1820REGISTRY.setManager(address(this), _newManager); } } pragma solidity 0.5.8; import "./SafeMath.sol"; import "./SafeGuard.sol"; import "./IERC644.sol"; /** * @title ERC644 Standard Balances Contract * @author chrisfranko */ contract ERC644Balances is IERC644, SafeGuard { using SafeMath for uint256; uint256 public totalSupply; event BalanceAdj(address indexed module, address indexed account, uint amount, string polarity); event ModuleSet(address indexed module, bool indexed set); mapping(address => bool) public modules; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; modifier onlyModule() { require(modules[msg.sender], "ERC644Balances: caller is not a module"); _; } /** * @notice Set allowance of `_spender` in behalf of `_sender` at `_value` * @param _sender Owner account * @param _spender Spender account * @param _value Value to approve * @return Operation status */ function setApprove(address _sender, address _spender, uint256 _value) external onlyModule returns (bool) { allowed[_sender][_spender] = _value; return true; } /** * @notice Decrease allowance of `_spender` in behalf of `_from` at `_value` * @param _from Owner account * @param _spender Spender account * @param _value Value to decrease * @return Operation status */ function decApprove(address _from, address _spender, uint _value) external onlyModule returns (bool) { allowed[_from][_spender] = allowed[_from][_spender].sub(_value); return true; } /** * @notice Increase total supply by `_val` * @param _val Value to increase * @return Operation status */ function incTotalSupply(uint _val) external onlyModule returns (bool) { totalSupply = totalSupply.add(_val); return true; } /** * @notice Decrease total supply by `_val` * @param _val Value to decrease * @return Operation status */ function decTotalSupply(uint _val) external onlyModule returns (bool) { totalSupply = totalSupply.sub(_val); return true; } /** * @notice Set/Unset `_acct` as an authorized module * @param _acct Module address * @param _set Module set status * @return Operation status */ function setModule(address _acct, bool _set) external onlyOwner returns (bool) { modules[_acct] = _set; emit ModuleSet(_acct, _set); return true; } /** * @notice Get `_acct` balance * @param _acct Target account to get balance. * @return The account balance */ function getBalance(address _acct) external view returns (uint256) { return balances[_acct]; } /** * @notice Get allowance of `_spender` in behalf of `_owner` * @param _owner Owner account * @param _spender Spender account * @return Allowance */ function getAllowance(address _owner, address _spender) external view returns (uint256) { return allowed[_owner][_spender]; } /** * @notice Get if `_acct` is an authorized module * @param _acct Module address * @return Operation status */ function getModule(address _acct) external view returns (bool) { return modules[_acct]; } /** * @notice Get total supply * @return Total supply */ function getTotalSupply() external view returns (uint256) { return totalSupply; } /** * @notice Increment `_acct` balance by `_val` * @param _acct Target account to increment balance. * @param _val Value to increment * @return Operation status */ function incBalance(address _acct, uint _val) public onlyModule returns (bool) { balances[_acct] = balances[_acct].add(_val); emit BalanceAdj(msg.sender, _acct, _val, "+"); return true; } /** * @notice Decrement `_acct` balance by `_val` * @param _acct Target account to decrement balance. * @param _val Value to decrement * @return Operation status */ function decBalance(address _acct, uint _val) public onlyModule returns (bool) { balances[_acct] = balances[_acct].sub(_val); emit BalanceAdj(msg.sender, _acct, _val, "-"); return true; } function transferRoot(address _new) external returns (bool) { return false; } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pragma solidity 0.5.8; import { ERC1820Client } from "./ERC1820Client.sol"; import { SafeMath } from "./SafeMath.sol"; import { IERC777 } from "./IERC777.sol"; import { IERC777TokensSender } from "./IERC777TokensSender.sol"; import { IERC777TokensRecipient } from "./IERC777TokensRecipient.sol"; contract ERC777 is IERC777, ERC1820Client { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; mapping(address => mapping(address => bool)) internal mAuthorizedOperators; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor( string memory _name, string memory _symbol, uint256 _granularity, address[] memory _defaultOperators ) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1, "Granularity must be > 1"); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint256 i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", address(this)); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public view returns (string memory) { return mName; } /// @return the symbol of the token function symbol() public view returns (string memory) { return mSymbol; } /// @return the granularity of the token function granularity() public view returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public view returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public view returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[] memory) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_data` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes calldata _data) external { doSend(msg.sender, msg.sender, _to, _amount, _data, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) external { require(_operator != msg.sender, "Cannot authorize yourself as an operator"); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorizedOperators[_operator][msg.sender] = true; } emit AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) external { require(_operator != msg.sender, "Cannot revoke yourself as an operator"); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorizedOperators[_operator][msg.sender] = false; } emit RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) { return (_operator == _tokenHolder // solium-disable-line operator-whitespace || mAuthorizedOperators[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend( address _from, address _to, uint256 _amount, bytes calldata _data, bytes calldata _operatorData ) external { require(isOperatorFor(msg.sender, _from), "Not an operator."); doSend(msg.sender, _from, _to, _amount, _data, _operatorData, true); } function burn(uint256 _amount, bytes calldata _data) external { doBurn(msg.sender, msg.sender, _amount, _data, ""); } function operatorBurn( address _tokenHolder, uint256 _amount, bytes calldata _data, bytes calldata _operatorData ) external { require(isOperatorFor(msg.sender, _tokenHolder), "Not an operator"); doBurn(msg.sender, _tokenHolder, _amount, _data, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount % mGranularity == 0, "Amount is not a multiple of granularity"); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal view returns(bool) { if (_addr == address(0)) { return false; } uint size; assembly { size := extcodesize(_addr) } // solium-disable-line security/no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777tokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _data, _operatorData); require(_to != address(0), "Cannot send to 0x0"); require(mBalances[_from] >= _amount, "Not enough funds"); mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking); emit Sent(_operator, _from, _to, _amount, _data, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _data Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn( address _operator, address _tokenHolder, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { callSender(_operator, _tokenHolder, address(0), _amount, _data, _operatorData); requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount, "Not enough funds"); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); emit Burned(_operator, _tokenHolder, _amount, _data, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != address(0)) { IERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _data, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to), "Cannot send to contract without ERC777TokensRecipient"); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _data Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == address(0)) { return; } IERC777TokensSender(senderImplementation).tokensToSend( _operator, _from, _to, _amount, _data, _operatorData); } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pragma solidity 0.5.8; import { IERC20 } from "./IERC20.sol"; import { ERC777RemoteBridge } from "./ERC777RemoteBridge.sol"; contract ERC777ERC20Compat is IERC20, ERC777RemoteBridge { bool internal mErc20compatible; mapping(address => mapping(address => uint256)) internal mAllowed; constructor( string memory _name, string memory _symbol, uint256 _granularity, uint256 _totalSupply, address _initialOwner, address[] memory _defaultOperators ) internal ERC777RemoteBridge(_name, _symbol, _granularity, _totalSupply, _initialOwner, _defaultOperators) { mErc20compatible = true; setInterfaceImplementation("ERC20Token", address(this)); } /// @notice This modifier is applied to erc20 obsolete methods that are /// implemented only to maintain backwards compatibility. When the erc20 /// compatibility is disabled, this methods will fail. modifier erc20 () { require(mErc20compatible, "ERC20 is disabled"); _; } /// @notice For Backwards compatibility /// @return The decimals of the token. Forced to 18 in ERC777. function decimals() public erc20 view returns (uint8) { return uint8(18); } /// @notice ERC20 backwards compatible transfer. /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transfer(address _to, uint256 _amount) public erc20 returns (bool success) { doSend(msg.sender, msg.sender, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible transferFrom. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { uint256 allowance = balancesDB.getAllowance(_from, msg.sender); require(_amount <= allowance, "Not enough allowance."); // Cannot be after doSend because of tokensReceived re-entry require(balancesDB.decApprove(_from, msg.sender, _amount)); doSend(msg.sender, _from, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible approve. /// `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf. /// @param _spender The address of the account able to transfer the tokens /// @param _amount The number of tokens to be approved for transfer /// @return `true`, if the approve can't be done, it should fail. function approve(address _spender, uint256 _amount) public erc20 returns (bool success) { require(balancesDB.setApprove(msg.sender, _spender, _amount)); emit Approval(msg.sender, _spender, _amount); return true; } /// @notice ERC20 backwards compatible allowance. /// This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public erc20 view returns (uint256 remaining) { return balancesDB.getAllowance(_owner, _spender); } function doSend( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { super.doSend(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking); if (mErc20compatible) { emit Transfer(_from, _to, _amount); } } function doBurn( address _operator, address _tokenHolder, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { super.doBurn(_operator, _tokenHolder, _amount, _data, _operatorData); if (mErc20compatible) { emit Transfer(_tokenHolder, address(0), _amount); } } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pragma solidity 0.5.8; import { ERC777 } from "./ERC777.sol"; import { CStore } from "./CStore.sol"; contract ERC777RemoteBridge is ERC777 { CStore public balancesDB; constructor( string memory _name, string memory _symbol, uint256 _granularity, uint256 _totalSupply, address _initialOwner, address[] memory _defaultOperators ) public ERC777(_name, _symbol, _granularity, new address[](0)) { balancesDB = new CStore(_totalSupply, _initialOwner, _defaultOperators); } /** * @return the total supply of the token */ function totalSupply() public view returns (uint256) { return balancesDB.getTotalSupply(); } /** * @notice Return the account balance of some account * @param _tokenHolder Address for which the balance is returned * @return the balance of `_tokenAddress`. */ function balanceOf(address _tokenHolder) public view returns (uint256) { return balancesDB.getBalance(_tokenHolder); } /** * @notice Return the list of default operators * @return the list of all the default operators */ function defaultOperators() public view returns (address[] memory) { return balancesDB.getDefaultOperators(); } /** * @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens at remote database. * @param _operator The operator that wants to be Authorized */ function authorizeOperator(address _operator) external { require(_operator != msg.sender, "Cannot authorize yourself as an operator"); if (balancesDB.getDefaultOperator(_operator)) { require(balancesDB.setRevokedDefaultOperator(_operator, msg.sender, false)); } else { require(balancesDB.setAuthorizedOperator(_operator, msg.sender, true)); } emit AuthorizedOperator(_operator, msg.sender); } /** * @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens at remote database. * @param _operator The operator that wants to be Revoked */ function revokeOperator(address _operator) external { require(_operator != msg.sender, "Cannot revoke yourself as an operator"); if (balancesDB.getDefaultOperator(_operator)) { require(balancesDB.setRevokedDefaultOperator(_operator, msg.sender, true)); } else { require(balancesDB.setAuthorizedOperator(_operator, msg.sender, false)); } emit RevokedOperator(_operator, msg.sender); } /** * @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` * address at remote database. * @param _operator address to check if it has the right to manage the tokens * @param _tokenHolder address which holds the tokens to be managed * @return `true` if `_operator` is authorized for `_tokenHolder` */ function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) { return _operator == _tokenHolder || balancesDB.getAuthorizedOperator(_operator, _tokenHolder); return (_operator == _tokenHolder // solium-disable-line operator-whitespace || balancesDB.getAuthorizedOperator(_operator, _tokenHolder) || (balancesDB.getDefaultOperator(_operator) && !balancesDB.getRevokedDefaultOperator(_operator, _tokenHolder))); } /** * @notice Helper function actually performing the sending of tokens using a backend database. * @param _from The address holding the tokens being sent * @param _to The address of the recipient * @param _amount The number of tokens to be sent * @param _data Data generated by the user to be passed to the recipient * @param _operatorData Data generated by the operator to be passed to the recipient * @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not * implementing `erc777_tokenHolder`. * ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer * functions SHOULD set this parameter to `false`. */ function doSend( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _data, _operatorData); require(_to != address(0), "Cannot send to 0x0"); // forbid sending to 0x0 (=burning) // require(mBalances[_from] >= _amount); // ensure enough funds // (Not Required due to SafeMath throw if underflow in database and false check) require(balancesDB.move(_from, _to, _amount)); callRecipient(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking); emit Sent(_operator, _from, _to, _amount, _data, _operatorData); //if (mErc20compatible) { emit Transfer(_from, _to, _amount); } } /** * @notice Helper function actually performing the burning of tokens. * @param _operator The address performing the burn * @param _tokenHolder The address holding the tokens being burn * @param _amount The number of tokens to be burnt * @param _data Data generated by the token holder * @param _operatorData Data generated by the operator */ function doBurn( address _operator, address _tokenHolder, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { revert("Burning functionality is disabled."); } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity 0.5.8; interface IERC644 { function getBalance(address _acct) external view returns(uint); function incBalance(address _acct, uint _val) external returns(bool); function decBalance(address _acct, uint _val) external returns(bool); function getAllowance(address _owner, address _spender) external view returns(uint); function setApprove(address _sender, address _spender, uint256 _value) external returns(bool); function decApprove(address _from, address _spender, uint _value) external returns(bool); function getModule(address _acct) external view returns (bool); function setModule(address _acct, bool _set) external returns(bool); function getTotalSupply() external view returns(uint); function incTotalSupply(uint _val) external returns(bool); function decTotalSupply(uint _val) external returns(bool); function transferRoot(address _new) external returns(bool); event BalanceAdj(address indexed Module, address indexed Account, uint Amount, string Polarity); event ModuleSet(address indexed Module, bool indexed Set); } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed pragma solidity 0.5.8; interface IERC777 { function name() external view returns (string memory); function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function granularity() external view returns (uint256); function defaultOperators() external view returns (address[] memory); function isOperatorFor(address operator, address tokenHolder) external view returns (bool); function authorizeOperator(address operator) external; function revokeOperator(address operator) external; function send(address to, uint256 amount, bytes calldata data) external; function operatorSend( address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; function burn(uint256 amount, bytes calldata data) external; function operatorBurn(address from, uint256 amount, bytes calldata data, bytes calldata operatorData) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed pragma solidity 0.5.8; interface IERC777TokensRecipient { function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed pragma solidity 0.5.8; interface IERC777TokensSender { function tokensToSend( address operator, address from, address to, uint amount, bytes calldata data, bytes calldata operatorData ) external; } pragma solidity ^0.5.0; import "./Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity 0.5.8; import "./Ownable.sol"; /** * @title Safe Guard Contract * @author Panos */ contract SafeGuard is Ownable { event Transaction(address indexed destination, uint value, bytes data); /** * @dev Allows owner to execute a transaction. */ function executeTransaction(address destination, uint value, bytes memory data) public onlyOwner { require(externalCall(destination, value, data.length, data)); emit Transaction(destination, value, data); } /** * @dev call has been separated into its own function in order to take advantage * of the Solidity's code generator to produce a loop that copies tx.data into memory. */ function externalCall(address destination, uint value, uint dataLength, bytes memory data) private returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly let x := mload(0x40) // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity 0.5.8; import "./ERC777ERC20Compat.sol"; import "./SafeGuard.sol"; import { CStore } from "./CStore.sol"; //TODO: Convert all imports like this contract CALL is ERC777ERC20Compat, SafeGuard { constructor( string memory _name, string memory _symbol, uint256 _granularity, uint256 _totalSupply, address _initialOwner, address[] memory _defaultOperators ) public ERC777ERC20Compat(_name, _symbol, _granularity, _totalSupply, _initialOwner, _defaultOperators) { requireMultiple(_totalSupply); require(balancesDB.setModule(address(this), true), "Cannot enable access to the database."); balancesDB.transferOwnership(_initialOwner); callRecipient(msg.sender, address(0), _initialOwner, _totalSupply, "", "", true); emit Minted(msg.sender, _initialOwner, _totalSupply, "", ""); if (mErc20compatible) { emit Transfer(address(0), _initialOwner, _totalSupply); } } /** * @notice change the balances database to `_newDB` * @param _newDB The new balances database address */ function changeBalancesDB(address _newDB) public onlyOwner { balancesDB = CStore(_newDB); } /** * @notice Disables the ERC20 interface. This function can only be called * by the owner. */ function disableERC20() public onlyOwner { mErc20compatible = false; setInterfaceImplementation("ERC20Token", address(0)); } /** * @notice Re enables the ERC20 interface. This function can only be called * by the owner. */ function enableERC20() public onlyOwner { mErc20compatible = true; setInterfaceImplementation("ERC20Token", address(this)); } /** * @dev Transfer the specified amounts of tokens to the specified addresses. * @dev Be aware that there is no check for duplicate recipients. * @param _toAddresses Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. */ function multiPartyTransfer(address[] calldata _toAddresses, uint256[] calldata _amounts) external erc20 { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255, "Unsupported number of addresses."); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length, "Provided addresses does not equal to provided sums."); for (uint8 i = 0; i < _toAddresses.length; i++) { transfer(_toAddresses[i], _amounts[i]); } } /** * @dev Transfer the specified amounts of tokens to the specified addresses from authorized balance of sender. * @dev Be aware that there is no check for duplicate recipients. * @param _from The address of the sender * @param _toAddresses The addresses of the recipients (MAX 255) * @param _amounts The amounts of tokens to be transferred */ function multiPartyTransferFrom(address _from, address[] calldata _toAddresses, uint256[] calldata _amounts) external erc20 { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255, "Unsupported number of addresses."); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length, "Provided addresses does not equal to provided sums."); for (uint8 i = 0; i < _toAddresses.length; i++) { transferFrom(_from, _toAddresses[i], _amounts[i]); } } /** * @dev Transfer the specified amounts of tokens to the specified addresses. * @dev Be aware that there is no check for duplicate recipients. * @param _toAddresses Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. * @param _userData User supplied data */ function multiPartySend(address[] memory _toAddresses, uint256[] memory _amounts, bytes memory _userData) public { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255, "Unsupported number of addresses."); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length, "Provided addresses does not equal to provided sums."); for (uint8 i = 0; i < _toAddresses.length; i++) { doSend(msg.sender, msg.sender, _toAddresses[i], _amounts[i], _userData, "", true); } } /** * @dev Transfer the specified amounts of tokens to the specified addresses as `_from`. * @dev Be aware that there is no check for duplicate recipients. * @param _from Address to use as sender * @param _to Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. * @param _userData User supplied data * @param _operatorData Operator supplied data */ function multiOperatorSend(address _from, address[] calldata _to, uint256[] calldata _amounts, bytes calldata _userData, bytes calldata _operatorData) external { /* Ensures _toAddresses array is less than or equal to 255 */ require(_to.length <= 255, "Unsupported number of addresses."); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_to.length == _amounts.length, "Provided addresses does not equal to provided sums."); for (uint8 i = 0; i < _to.length; i++) { require(isOperatorFor(msg.sender, _from), "Not an operator"); //TODO check for denial of service doSend(msg.sender, _from, _to[i], _amounts[i], _userData, _operatorData, true); } } } pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity 0.5.8; import "./ERC644Balances.sol"; import { ERC1820Client } from "./ERC1820Client.sol"; /** * @title ERC644 Database Contract * @author Panos */ contract CStore is ERC644Balances, ERC1820Client { address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; mapping(address => mapping(address => bool)) internal mAuthorizedOperators; /** * @notice Database construction * @param _totalSupply The total supply of the token */ constructor(uint256 _totalSupply, address _initialOwner, address[] memory _defaultOperators) public { balances[_initialOwner] = _totalSupply; totalSupply = _totalSupply; mDefaultOperators = _defaultOperators; for (uint256 i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC644Balances", address(this)); } /** * @notice Increase total supply by `_val` * @param _val Value to increase * @return Operation status */ // solhint-disable-next-line no-unused-vars function incTotalSupply(uint _val) external onlyModule returns (bool) { return false; } /** * @notice Decrease total supply by `_val` * @param _val Value to decrease * @return Operation status */ // solhint-disable-next-line no-unused-vars function decTotalSupply(uint _val) external onlyModule returns (bool) { return false; } /** * @notice moving `_amount` from `_from` to `_to` * @param _from The sender address * @param _to The receiving address * @param _amount The moving amount * @return bool The move result */ function move(address _from, address _to, uint256 _amount) external onlyModule returns (bool) { balances[_from] = balances[_from].sub(_amount); emit BalanceAdj(msg.sender, _from, _amount, "-"); balances[_to] = balances[_to].add(_amount); emit BalanceAdj(msg.sender, _to, _amount, "+"); return true; } /** * @notice Setting operator `_operator` for `_tokenHolder` * @param _operator The operator to set status * @param _tokenHolder The token holder to set operator * @param _status The operator status * @return bool Status of operation */ function setAuthorizedOperator(address _operator, address _tokenHolder, bool _status) external onlyModule returns (bool) { mAuthorizedOperators[_operator][_tokenHolder] = _status; return true; } /** * @notice Set revoke status for default operator `_operator` for `_tokenHolder` * @param _operator The default operator to set status * @param _tokenHolder The token holder to set operator * @param _status The operator status * @return bool Status of operation */ function setRevokedDefaultOperator(address _operator, address _tokenHolder, bool _status) external onlyModule returns (bool) { mRevokedDefaultOperator[_operator][_tokenHolder] = _status; return true; } /** * @notice Getting operator `_operator` for `_tokenHolder` * @param _operator The operator address to get status * @param _tokenHolder The token holder address * @return bool Operator status */ function getAuthorizedOperator(address _operator, address _tokenHolder) external view returns (bool) { return mAuthorizedOperators[_operator][_tokenHolder]; } /** * @notice Getting default operator `_operator` * @param _operator The default operator address to get status * @return bool Default operator status */ function getDefaultOperator(address _operator) external view returns (bool) { return mIsDefaultOperator[_operator]; } /** * @notice Getting default operators * @return address[] Default operator addresses */ function getDefaultOperators() external view returns (address[] memory) { return mDefaultOperators; } function getRevokedDefaultOperator(address _operator, address _tokenHolder) external view returns (bool) { return mRevokedDefaultOperator[_operator][_tokenHolder]; } /** * @notice Increment `_acct` balance by `_val` * @param _acct Target account to increment balance. * @param _val Value to increment * @return Operation status */ // solhint-disable-next-line no-unused-vars function incBalance(address _acct, uint _val) public onlyModule returns (bool) { return false; } /** * @notice Decrement `_acct` balance by `_val` * @param _acct Target account to decrement balance. * @param _val Value to decrement * @return Operation status */ // solhint-disable-next-line no-unused-vars function decBalance(address _acct, uint _val) public onlyModule returns (bool) { return false; } } pragma solidity ^0.5.3; contract ERC1820Registry { function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external; function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address); function setManager(address _addr, address _newManager) external; function getManager(address _addr) public view returns (address); } /// Base client to interact with the registry. contract ERC1820Client { ERC1820Registry constant ERC1820REGISTRY = ERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); function setInterfaceImplementation(string memory _interfaceLabel, address _implementation) internal { bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel)); ERC1820REGISTRY.setInterfaceImplementer(address(this), interfaceHash, _implementation); } function interfaceAddr(address addr, string memory _interfaceLabel) internal view returns(address) { bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel)); return ERC1820REGISTRY.getInterfaceImplementer(addr, interfaceHash); } function delegateManagement(address _newManager) internal { ERC1820REGISTRY.setManager(address(this), _newManager); } } pragma solidity 0.5.8; import "./SafeMath.sol"; import "./SafeGuard.sol"; import "./IERC644.sol"; /** * @title ERC644 Standard Balances Contract * @author chrisfranko */ contract ERC644Balances is IERC644, SafeGuard { using SafeMath for uint256; uint256 public totalSupply; event BalanceAdj(address indexed module, address indexed account, uint amount, string polarity); event ModuleSet(address indexed module, bool indexed set); mapping(address => bool) public modules; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; modifier onlyModule() { require(modules[msg.sender], "ERC644Balances: caller is not a module"); _; } /** * @notice Set allowance of `_spender` in behalf of `_sender` at `_value` * @param _sender Owner account * @param _spender Spender account * @param _value Value to approve * @return Operation status */ function setApprove(address _sender, address _spender, uint256 _value) external onlyModule returns (bool) { allowed[_sender][_spender] = _value; return true; } /** * @notice Decrease allowance of `_spender` in behalf of `_from` at `_value` * @param _from Owner account * @param _spender Spender account * @param _value Value to decrease * @return Operation status */ function decApprove(address _from, address _spender, uint _value) external onlyModule returns (bool) { allowed[_from][_spender] = allowed[_from][_spender].sub(_value); return true; } /** * @notice Increase total supply by `_val` * @param _val Value to increase * @return Operation status */ function incTotalSupply(uint _val) external onlyModule returns (bool) { totalSupply = totalSupply.add(_val); return true; } /** * @notice Decrease total supply by `_val` * @param _val Value to decrease * @return Operation status */ function decTotalSupply(uint _val) external onlyModule returns (bool) { totalSupply = totalSupply.sub(_val); return true; } /** * @notice Set/Unset `_acct` as an authorized module * @param _acct Module address * @param _set Module set status * @return Operation status */ function setModule(address _acct, bool _set) external onlyOwner returns (bool) { modules[_acct] = _set; emit ModuleSet(_acct, _set); return true; } /** * @notice Get `_acct` balance * @param _acct Target account to get balance. * @return The account balance */ function getBalance(address _acct) external view returns (uint256) { return balances[_acct]; } /** * @notice Get allowance of `_spender` in behalf of `_owner` * @param _owner Owner account * @param _spender Spender account * @return Allowance */ function getAllowance(address _owner, address _spender) external view returns (uint256) { return allowed[_owner][_spender]; } /** * @notice Get if `_acct` is an authorized module * @param _acct Module address * @return Operation status */ function getModule(address _acct) external view returns (bool) { return modules[_acct]; } /** * @notice Get total supply * @return Total supply */ function getTotalSupply() external view returns (uint256) { return totalSupply; } /** * @notice Increment `_acct` balance by `_val` * @param _acct Target account to increment balance. * @param _val Value to increment * @return Operation status */ function incBalance(address _acct, uint _val) public onlyModule returns (bool) { balances[_acct] = balances[_acct].add(_val); emit BalanceAdj(msg.sender, _acct, _val, "+"); return true; } /** * @notice Decrement `_acct` balance by `_val` * @param _acct Target account to decrement balance. * @param _val Value to decrement * @return Operation status */ function decBalance(address _acct, uint _val) public onlyModule returns (bool) { balances[_acct] = balances[_acct].sub(_val); emit BalanceAdj(msg.sender, _acct, _val, "-"); return true; } function transferRoot(address _new) external returns (bool) { return false; } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pragma solidity 0.5.8; import { ERC1820Client } from "./ERC1820Client.sol"; import { SafeMath } from "./SafeMath.sol"; import { IERC777 } from "./IERC777.sol"; import { IERC777TokensSender } from "./IERC777TokensSender.sol"; import { IERC777TokensRecipient } from "./IERC777TokensRecipient.sol"; contract ERC777 is IERC777, ERC1820Client { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; mapping(address => mapping(address => bool)) internal mAuthorizedOperators; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor( string memory _name, string memory _symbol, uint256 _granularity, address[] memory _defaultOperators ) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1, "Granularity must be > 1"); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint256 i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", address(this)); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public view returns (string memory) { return mName; } /// @return the symbol of the token function symbol() public view returns (string memory) { return mSymbol; } /// @return the granularity of the token function granularity() public view returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public view returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public view returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[] memory) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_data` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes calldata _data) external { doSend(msg.sender, msg.sender, _to, _amount, _data, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) external { require(_operator != msg.sender, "Cannot authorize yourself as an operator"); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorizedOperators[_operator][msg.sender] = true; } emit AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) external { require(_operator != msg.sender, "Cannot revoke yourself as an operator"); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorizedOperators[_operator][msg.sender] = false; } emit RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) { return (_operator == _tokenHolder // solium-disable-line operator-whitespace || mAuthorizedOperators[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend( address _from, address _to, uint256 _amount, bytes calldata _data, bytes calldata _operatorData ) external { require(isOperatorFor(msg.sender, _from), "Not an operator."); doSend(msg.sender, _from, _to, _amount, _data, _operatorData, true); } function burn(uint256 _amount, bytes calldata _data) external { doBurn(msg.sender, msg.sender, _amount, _data, ""); } function operatorBurn( address _tokenHolder, uint256 _amount, bytes calldata _data, bytes calldata _operatorData ) external { require(isOperatorFor(msg.sender, _tokenHolder), "Not an operator"); doBurn(msg.sender, _tokenHolder, _amount, _data, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount % mGranularity == 0, "Amount is not a multiple of granularity"); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal view returns(bool) { if (_addr == address(0)) { return false; } uint size; assembly { size := extcodesize(_addr) } // solium-disable-line security/no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777tokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _data, _operatorData); require(_to != address(0), "Cannot send to 0x0"); require(mBalances[_from] >= _amount, "Not enough funds"); mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking); emit Sent(_operator, _from, _to, _amount, _data, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _data Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn( address _operator, address _tokenHolder, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { callSender(_operator, _tokenHolder, address(0), _amount, _data, _operatorData); requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount, "Not enough funds"); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); emit Burned(_operator, _tokenHolder, _amount, _data, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != address(0)) { IERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _data, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to), "Cannot send to contract without ERC777TokensRecipient"); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _data Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == address(0)) { return; } IERC777TokensSender(senderImplementation).tokensToSend( _operator, _from, _to, _amount, _data, _operatorData); } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pragma solidity 0.5.8; import { IERC20 } from "./IERC20.sol"; import { ERC777RemoteBridge } from "./ERC777RemoteBridge.sol"; contract ERC777ERC20Compat is IERC20, ERC777RemoteBridge { bool internal mErc20compatible; mapping(address => mapping(address => uint256)) internal mAllowed; constructor( string memory _name, string memory _symbol, uint256 _granularity, uint256 _totalSupply, address _initialOwner, address[] memory _defaultOperators ) internal ERC777RemoteBridge(_name, _symbol, _granularity, _totalSupply, _initialOwner, _defaultOperators) { mErc20compatible = true; setInterfaceImplementation("ERC20Token", address(this)); } /// @notice This modifier is applied to erc20 obsolete methods that are /// implemented only to maintain backwards compatibility. When the erc20 /// compatibility is disabled, this methods will fail. modifier erc20 () { require(mErc20compatible, "ERC20 is disabled"); _; } /// @notice For Backwards compatibility /// @return The decimals of the token. Forced to 18 in ERC777. function decimals() public erc20 view returns (uint8) { return uint8(18); } /// @notice ERC20 backwards compatible transfer. /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transfer(address _to, uint256 _amount) public erc20 returns (bool success) { doSend(msg.sender, msg.sender, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible transferFrom. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { uint256 allowance = balancesDB.getAllowance(_from, msg.sender); require(_amount <= allowance, "Not enough allowance."); // Cannot be after doSend because of tokensReceived re-entry require(balancesDB.decApprove(_from, msg.sender, _amount)); doSend(msg.sender, _from, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible approve. /// `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf. /// @param _spender The address of the account able to transfer the tokens /// @param _amount The number of tokens to be approved for transfer /// @return `true`, if the approve can't be done, it should fail. function approve(address _spender, uint256 _amount) public erc20 returns (bool success) { require(balancesDB.setApprove(msg.sender, _spender, _amount)); emit Approval(msg.sender, _spender, _amount); return true; } /// @notice ERC20 backwards compatible allowance. /// This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public erc20 view returns (uint256 remaining) { return balancesDB.getAllowance(_owner, _spender); } function doSend( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { super.doSend(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking); if (mErc20compatible) { emit Transfer(_from, _to, _amount); } } function doBurn( address _operator, address _tokenHolder, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { super.doBurn(_operator, _tokenHolder, _amount, _data, _operatorData); if (mErc20compatible) { emit Transfer(_tokenHolder, address(0), _amount); } } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pragma solidity 0.5.8; import { ERC777 } from "./ERC777.sol"; import { CStore } from "./CStore.sol"; contract ERC777RemoteBridge is ERC777 { CStore public balancesDB; constructor( string memory _name, string memory _symbol, uint256 _granularity, uint256 _totalSupply, address _initialOwner, address[] memory _defaultOperators ) public ERC777(_name, _symbol, _granularity, new address[](0)) { balancesDB = new CStore(_totalSupply, _initialOwner, _defaultOperators); } /** * @return the total supply of the token */ function totalSupply() public view returns (uint256) { return balancesDB.getTotalSupply(); } /** * @notice Return the account balance of some account * @param _tokenHolder Address for which the balance is returned * @return the balance of `_tokenAddress`. */ function balanceOf(address _tokenHolder) public view returns (uint256) { return balancesDB.getBalance(_tokenHolder); } /** * @notice Return the list of default operators * @return the list of all the default operators */ function defaultOperators() public view returns (address[] memory) { return balancesDB.getDefaultOperators(); } /** * @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens at remote database. * @param _operator The operator that wants to be Authorized */ function authorizeOperator(address _operator) external { require(_operator != msg.sender, "Cannot authorize yourself as an operator"); if (balancesDB.getDefaultOperator(_operator)) { require(balancesDB.setRevokedDefaultOperator(_operator, msg.sender, false)); } else { require(balancesDB.setAuthorizedOperator(_operator, msg.sender, true)); } emit AuthorizedOperator(_operator, msg.sender); } /** * @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens at remote database. * @param _operator The operator that wants to be Revoked */ function revokeOperator(address _operator) external { require(_operator != msg.sender, "Cannot revoke yourself as an operator"); if (balancesDB.getDefaultOperator(_operator)) { require(balancesDB.setRevokedDefaultOperator(_operator, msg.sender, true)); } else { require(balancesDB.setAuthorizedOperator(_operator, msg.sender, false)); } emit RevokedOperator(_operator, msg.sender); } /** * @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` * address at remote database. * @param _operator address to check if it has the right to manage the tokens * @param _tokenHolder address which holds the tokens to be managed * @return `true` if `_operator` is authorized for `_tokenHolder` */ function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) { return _operator == _tokenHolder || balancesDB.getAuthorizedOperator(_operator, _tokenHolder); return (_operator == _tokenHolder // solium-disable-line operator-whitespace || balancesDB.getAuthorizedOperator(_operator, _tokenHolder) || (balancesDB.getDefaultOperator(_operator) && !balancesDB.getRevokedDefaultOperator(_operator, _tokenHolder))); } /** * @notice Helper function actually performing the sending of tokens using a backend database. * @param _from The address holding the tokens being sent * @param _to The address of the recipient * @param _amount The number of tokens to be sent * @param _data Data generated by the user to be passed to the recipient * @param _operatorData Data generated by the operator to be passed to the recipient * @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not * implementing `erc777_tokenHolder`. * ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer * functions SHOULD set this parameter to `false`. */ function doSend( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _data, _operatorData); require(_to != address(0), "Cannot send to 0x0"); // forbid sending to 0x0 (=burning) // require(mBalances[_from] >= _amount); // ensure enough funds // (Not Required due to SafeMath throw if underflow in database and false check) require(balancesDB.move(_from, _to, _amount)); callRecipient(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking); emit Sent(_operator, _from, _to, _amount, _data, _operatorData); //if (mErc20compatible) { emit Transfer(_from, _to, _amount); } } /** * @notice Helper function actually performing the burning of tokens. * @param _operator The address performing the burn * @param _tokenHolder The address holding the tokens being burn * @param _amount The number of tokens to be burnt * @param _data Data generated by the token holder * @param _operatorData Data generated by the operator */ function doBurn( address _operator, address _tokenHolder, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { revert("Burning functionality is disabled."); } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity 0.5.8; interface IERC644 { function getBalance(address _acct) external view returns(uint); function incBalance(address _acct, uint _val) external returns(bool); function decBalance(address _acct, uint _val) external returns(bool); function getAllowance(address _owner, address _spender) external view returns(uint); function setApprove(address _sender, address _spender, uint256 _value) external returns(bool); function decApprove(address _from, address _spender, uint _value) external returns(bool); function getModule(address _acct) external view returns (bool); function setModule(address _acct, bool _set) external returns(bool); function getTotalSupply() external view returns(uint); function incTotalSupply(uint _val) external returns(bool); function decTotalSupply(uint _val) external returns(bool); function transferRoot(address _new) external returns(bool); event BalanceAdj(address indexed Module, address indexed Account, uint Amount, string Polarity); event ModuleSet(address indexed Module, bool indexed Set); } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed pragma solidity 0.5.8; interface IERC777 { function name() external view returns (string memory); function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function granularity() external view returns (uint256); function defaultOperators() external view returns (address[] memory); function isOperatorFor(address operator, address tokenHolder) external view returns (bool); function authorizeOperator(address operator) external; function revokeOperator(address operator) external; function send(address to, uint256 amount, bytes calldata data) external; function operatorSend( address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; function burn(uint256 amount, bytes calldata data) external; function operatorBurn(address from, uint256 amount, bytes calldata data, bytes calldata operatorData) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed pragma solidity 0.5.8; interface IERC777TokensRecipient { function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed pragma solidity 0.5.8; interface IERC777TokensSender { function tokensToSend( address operator, address from, address to, uint amount, bytes calldata data, bytes calldata operatorData ) external; } pragma solidity ^0.5.0; import "./Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity 0.5.8; import "./Ownable.sol"; /** * @title Safe Guard Contract * @author Panos */ contract SafeGuard is Ownable { event Transaction(address indexed destination, uint value, bytes data); /** * @dev Allows owner to execute a transaction. */ function executeTransaction(address destination, uint value, bytes memory data) public onlyOwner { require(externalCall(destination, value, data.length, data)); emit Transaction(destination, value, data); } /** * @dev call has been separated into its own function in order to take advantage * of the Solidity's code generator to produce a loop that copies tx.data into memory. */ function externalCall(address destination, uint value, uint dataLength, bytes memory data) private returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly let x := mload(0x40) // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity 0.5.8; import "./ERC777ERC20Compat.sol"; import "./SafeGuard.sol"; import { CStore } from "./CStore.sol"; //TODO: Convert all imports like this contract CALL is ERC777ERC20Compat, SafeGuard { constructor( string memory _name, string memory _symbol, uint256 _granularity, uint256 _totalSupply, address _initialOwner, address[] memory _defaultOperators ) public ERC777ERC20Compat(_name, _symbol, _granularity, _totalSupply, _initialOwner, _defaultOperators) { requireMultiple(_totalSupply); require(balancesDB.setModule(address(this), true), "Cannot enable access to the database."); balancesDB.transferOwnership(_initialOwner); callRecipient(msg.sender, address(0), _initialOwner, _totalSupply, "", "", true); emit Minted(msg.sender, _initialOwner, _totalSupply, "", ""); if (mErc20compatible) { emit Transfer(address(0), _initialOwner, _totalSupply); } } /** * @notice change the balances database to `_newDB` * @param _newDB The new balances database address */ function changeBalancesDB(address _newDB) public onlyOwner { balancesDB = CStore(_newDB); } /** * @notice Disables the ERC20 interface. This function can only be called * by the owner. */ function disableERC20() public onlyOwner { mErc20compatible = false; setInterfaceImplementation("ERC20Token", address(0)); } /** * @notice Re enables the ERC20 interface. This function can only be called * by the owner. */ function enableERC20() public onlyOwner { mErc20compatible = true; setInterfaceImplementation("ERC20Token", address(this)); } /** * @dev Transfer the specified amounts of tokens to the specified addresses. * @dev Be aware that there is no check for duplicate recipients. * @param _toAddresses Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. */ function multiPartyTransfer(address[] calldata _toAddresses, uint256[] calldata _amounts) external erc20 { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255, "Unsupported number of addresses."); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length, "Provided addresses does not equal to provided sums."); for (uint8 i = 0; i < _toAddresses.length; i++) { transfer(_toAddresses[i], _amounts[i]); } } /** * @dev Transfer the specified amounts of tokens to the specified addresses from authorized balance of sender. * @dev Be aware that there is no check for duplicate recipients. * @param _from The address of the sender * @param _toAddresses The addresses of the recipients (MAX 255) * @param _amounts The amounts of tokens to be transferred */ function multiPartyTransferFrom(address _from, address[] calldata _toAddresses, uint256[] calldata _amounts) external erc20 { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255, "Unsupported number of addresses."); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length, "Provided addresses does not equal to provided sums."); for (uint8 i = 0; i < _toAddresses.length; i++) { transferFrom(_from, _toAddresses[i], _amounts[i]); } } /** * @dev Transfer the specified amounts of tokens to the specified addresses. * @dev Be aware that there is no check for duplicate recipients. * @param _toAddresses Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. * @param _userData User supplied data */ function multiPartySend(address[] memory _toAddresses, uint256[] memory _amounts, bytes memory _userData) public { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255, "Unsupported number of addresses."); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length, "Provided addresses does not equal to provided sums."); for (uint8 i = 0; i < _toAddresses.length; i++) { doSend(msg.sender, msg.sender, _toAddresses[i], _amounts[i], _userData, "", true); } } /** * @dev Transfer the specified amounts of tokens to the specified addresses as `_from`. * @dev Be aware that there is no check for duplicate recipients. * @param _from Address to use as sender * @param _to Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. * @param _userData User supplied data * @param _operatorData Operator supplied data */ function multiOperatorSend(address _from, address[] calldata _to, uint256[] calldata _amounts, bytes calldata _userData, bytes calldata _operatorData) external { /* Ensures _toAddresses array is less than or equal to 255 */ require(_to.length <= 255, "Unsupported number of addresses."); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_to.length == _amounts.length, "Provided addresses does not equal to provided sums."); for (uint8 i = 0; i < _to.length; i++) { require(isOperatorFor(msg.sender, _from), "Not an operator"); //TODO check for denial of service doSend(msg.sender, _from, _to[i], _amounts[i], _userData, _operatorData, true); } } } pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity 0.5.8; import "./ERC644Balances.sol"; import { ERC1820Client } from "./ERC1820Client.sol"; /** * @title ERC644 Database Contract * @author Panos */ contract CStore is ERC644Balances, ERC1820Client { address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; mapping(address => mapping(address => bool)) internal mAuthorizedOperators; /** * @notice Database construction * @param _totalSupply The total supply of the token */ constructor(uint256 _totalSupply, address _initialOwner, address[] memory _defaultOperators) public { balances[_initialOwner] = _totalSupply; totalSupply = _totalSupply; mDefaultOperators = _defaultOperators; for (uint256 i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC644Balances", address(this)); } /** * @notice Increase total supply by `_val` * @param _val Value to increase * @return Operation status */ // solhint-disable-next-line no-unused-vars function incTotalSupply(uint _val) external onlyModule returns (bool) { return false; } /** * @notice Decrease total supply by `_val` * @param _val Value to decrease * @return Operation status */ // solhint-disable-next-line no-unused-vars function decTotalSupply(uint _val) external onlyModule returns (bool) { return false; } /** * @notice moving `_amount` from `_from` to `_to` * @param _from The sender address * @param _to The receiving address * @param _amount The moving amount * @return bool The move result */ function move(address _from, address _to, uint256 _amount) external onlyModule returns (bool) { balances[_from] = balances[_from].sub(_amount); emit BalanceAdj(msg.sender, _from, _amount, "-"); balances[_to] = balances[_to].add(_amount); emit BalanceAdj(msg.sender, _to, _amount, "+"); return true; } /** * @notice Setting operator `_operator` for `_tokenHolder` * @param _operator The operator to set status * @param _tokenHolder The token holder to set operator * @param _status The operator status * @return bool Status of operation */ function setAuthorizedOperator(address _operator, address _tokenHolder, bool _status) external onlyModule returns (bool) { mAuthorizedOperators[_operator][_tokenHolder] = _status; return true; } /** * @notice Set revoke status for default operator `_operator` for `_tokenHolder` * @param _operator The default operator to set status * @param _tokenHolder The token holder to set operator * @param _status The operator status * @return bool Status of operation */ function setRevokedDefaultOperator(address _operator, address _tokenHolder, bool _status) external onlyModule returns (bool) { mRevokedDefaultOperator[_operator][_tokenHolder] = _status; return true; } /** * @notice Getting operator `_operator` for `_tokenHolder` * @param _operator The operator address to get status * @param _tokenHolder The token holder address * @return bool Operator status */ function getAuthorizedOperator(address _operator, address _tokenHolder) external view returns (bool) { return mAuthorizedOperators[_operator][_tokenHolder]; } /** * @notice Getting default operator `_operator` * @param _operator The default operator address to get status * @return bool Default operator status */ function getDefaultOperator(address _operator) external view returns (bool) { return mIsDefaultOperator[_operator]; } /** * @notice Getting default operators * @return address[] Default operator addresses */ function getDefaultOperators() external view returns (address[] memory) { return mDefaultOperators; } function getRevokedDefaultOperator(address _operator, address _tokenHolder) external view returns (bool) { return mRevokedDefaultOperator[_operator][_tokenHolder]; } /** * @notice Increment `_acct` balance by `_val` * @param _acct Target account to increment balance. * @param _val Value to increment * @return Operation status */ // solhint-disable-next-line no-unused-vars function incBalance(address _acct, uint _val) public onlyModule returns (bool) { return false; } /** * @notice Decrement `_acct` balance by `_val` * @param _acct Target account to decrement balance. * @param _val Value to decrement * @return Operation status */ // solhint-disable-next-line no-unused-vars function decBalance(address _acct, uint _val) public onlyModule returns (bool) { return false; } } pragma solidity ^0.5.3; contract ERC1820Registry { function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external; function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address); function setManager(address _addr, address _newManager) external; function getManager(address _addr) public view returns (address); } /// Base client to interact with the registry. contract ERC1820Client { ERC1820Registry constant ERC1820REGISTRY = ERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); function setInterfaceImplementation(string memory _interfaceLabel, address _implementation) internal { bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel)); ERC1820REGISTRY.setInterfaceImplementer(address(this), interfaceHash, _implementation); } function interfaceAddr(address addr, string memory _interfaceLabel) internal view returns(address) { bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel)); return ERC1820REGISTRY.getInterfaceImplementer(addr, interfaceHash); } function delegateManagement(address _newManager) internal { ERC1820REGISTRY.setManager(address(this), _newManager); } } pragma solidity 0.5.8; import "./SafeMath.sol"; import "./SafeGuard.sol"; import "./IERC644.sol"; /** * @title ERC644 Standard Balances Contract * @author chrisfranko */ contract ERC644Balances is IERC644, SafeGuard { using SafeMath for uint256; uint256 public totalSupply; event BalanceAdj(address indexed module, address indexed account, uint amount, string polarity); event ModuleSet(address indexed module, bool indexed set); mapping(address => bool) public modules; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; modifier onlyModule() { require(modules[msg.sender], "ERC644Balances: caller is not a module"); _; } /** * @notice Set allowance of `_spender` in behalf of `_sender` at `_value` * @param _sender Owner account * @param _spender Spender account * @param _value Value to approve * @return Operation status */ function setApprove(address _sender, address _spender, uint256 _value) external onlyModule returns (bool) { allowed[_sender][_spender] = _value; return true; } /** * @notice Decrease allowance of `_spender` in behalf of `_from` at `_value` * @param _from Owner account * @param _spender Spender account * @param _value Value to decrease * @return Operation status */ function decApprove(address _from, address _spender, uint _value) external onlyModule returns (bool) { allowed[_from][_spender] = allowed[_from][_spender].sub(_value); return true; } /** * @notice Increase total supply by `_val` * @param _val Value to increase * @return Operation status */ function incTotalSupply(uint _val) external onlyModule returns (bool) { totalSupply = totalSupply.add(_val); return true; } /** * @notice Decrease total supply by `_val` * @param _val Value to decrease * @return Operation status */ function decTotalSupply(uint _val) external onlyModule returns (bool) { totalSupply = totalSupply.sub(_val); return true; } /** * @notice Set/Unset `_acct` as an authorized module * @param _acct Module address * @param _set Module set status * @return Operation status */ function setModule(address _acct, bool _set) external onlyOwner returns (bool) { modules[_acct] = _set; emit ModuleSet(_acct, _set); return true; } /** * @notice Get `_acct` balance * @param _acct Target account to get balance. * @return The account balance */ function getBalance(address _acct) external view returns (uint256) { return balances[_acct]; } /** * @notice Get allowance of `_spender` in behalf of `_owner` * @param _owner Owner account * @param _spender Spender account * @return Allowance */ function getAllowance(address _owner, address _spender) external view returns (uint256) { return allowed[_owner][_spender]; } /** * @notice Get if `_acct` is an authorized module * @param _acct Module address * @return Operation status */ function getModule(address _acct) external view returns (bool) { return modules[_acct]; } /** * @notice Get total supply * @return Total supply */ function getTotalSupply() external view returns (uint256) { return totalSupply; } /** * @notice Increment `_acct` balance by `_val` * @param _acct Target account to increment balance. * @param _val Value to increment * @return Operation status */ function incBalance(address _acct, uint _val) public onlyModule returns (bool) { balances[_acct] = balances[_acct].add(_val); emit BalanceAdj(msg.sender, _acct, _val, "+"); return true; } /** * @notice Decrement `_acct` balance by `_val` * @param _acct Target account to decrement balance. * @param _val Value to decrement * @return Operation status */ function decBalance(address _acct, uint _val) public onlyModule returns (bool) { balances[_acct] = balances[_acct].sub(_val); emit BalanceAdj(msg.sender, _acct, _val, "-"); return true; } function transferRoot(address _new) external returns (bool) { return false; } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pragma solidity 0.5.8; import { ERC1820Client } from "./ERC1820Client.sol"; import { SafeMath } from "./SafeMath.sol"; import { IERC777 } from "./IERC777.sol"; import { IERC777TokensSender } from "./IERC777TokensSender.sol"; import { IERC777TokensRecipient } from "./IERC777TokensRecipient.sol"; contract ERC777 is IERC777, ERC1820Client { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; mapping(address => mapping(address => bool)) internal mAuthorizedOperators; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor( string memory _name, string memory _symbol, uint256 _granularity, address[] memory _defaultOperators ) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1, "Granularity must be > 1"); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint256 i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", address(this)); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public view returns (string memory) { return mName; } /// @return the symbol of the token function symbol() public view returns (string memory) { return mSymbol; } /// @return the granularity of the token function granularity() public view returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public view returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public view returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[] memory) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_data` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes calldata _data) external { doSend(msg.sender, msg.sender, _to, _amount, _data, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) external { require(_operator != msg.sender, "Cannot authorize yourself as an operator"); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorizedOperators[_operator][msg.sender] = true; } emit AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) external { require(_operator != msg.sender, "Cannot revoke yourself as an operator"); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorizedOperators[_operator][msg.sender] = false; } emit RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) { return (_operator == _tokenHolder // solium-disable-line operator-whitespace || mAuthorizedOperators[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend( address _from, address _to, uint256 _amount, bytes calldata _data, bytes calldata _operatorData ) external { require(isOperatorFor(msg.sender, _from), "Not an operator."); doSend(msg.sender, _from, _to, _amount, _data, _operatorData, true); } function burn(uint256 _amount, bytes calldata _data) external { doBurn(msg.sender, msg.sender, _amount, _data, ""); } function operatorBurn( address _tokenHolder, uint256 _amount, bytes calldata _data, bytes calldata _operatorData ) external { require(isOperatorFor(msg.sender, _tokenHolder), "Not an operator"); doBurn(msg.sender, _tokenHolder, _amount, _data, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount % mGranularity == 0, "Amount is not a multiple of granularity"); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal view returns(bool) { if (_addr == address(0)) { return false; } uint size; assembly { size := extcodesize(_addr) } // solium-disable-line security/no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777tokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _data, _operatorData); require(_to != address(0), "Cannot send to 0x0"); require(mBalances[_from] >= _amount, "Not enough funds"); mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking); emit Sent(_operator, _from, _to, _amount, _data, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _data Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn( address _operator, address _tokenHolder, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { callSender(_operator, _tokenHolder, address(0), _amount, _data, _operatorData); requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount, "Not enough funds"); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); emit Burned(_operator, _tokenHolder, _amount, _data, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != address(0)) { IERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _data, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to), "Cannot send to contract without ERC777TokensRecipient"); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _data Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == address(0)) { return; } IERC777TokensSender(senderImplementation).tokensToSend( _operator, _from, _to, _amount, _data, _operatorData); } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pragma solidity 0.5.8; import { IERC20 } from "./IERC20.sol"; import { ERC777RemoteBridge } from "./ERC777RemoteBridge.sol"; contract ERC777ERC20Compat is IERC20, ERC777RemoteBridge { bool internal mErc20compatible; mapping(address => mapping(address => uint256)) internal mAllowed; constructor( string memory _name, string memory _symbol, uint256 _granularity, uint256 _totalSupply, address _initialOwner, address[] memory _defaultOperators ) internal ERC777RemoteBridge(_name, _symbol, _granularity, _totalSupply, _initialOwner, _defaultOperators) { mErc20compatible = true; setInterfaceImplementation("ERC20Token", address(this)); } /// @notice This modifier is applied to erc20 obsolete methods that are /// implemented only to maintain backwards compatibility. When the erc20 /// compatibility is disabled, this methods will fail. modifier erc20 () { require(mErc20compatible, "ERC20 is disabled"); _; } /// @notice For Backwards compatibility /// @return The decimals of the token. Forced to 18 in ERC777. function decimals() public erc20 view returns (uint8) { return uint8(18); } /// @notice ERC20 backwards compatible transfer. /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transfer(address _to, uint256 _amount) public erc20 returns (bool success) { doSend(msg.sender, msg.sender, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible transferFrom. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { uint256 allowance = balancesDB.getAllowance(_from, msg.sender); require(_amount <= allowance, "Not enough allowance."); // Cannot be after doSend because of tokensReceived re-entry require(balancesDB.decApprove(_from, msg.sender, _amount)); doSend(msg.sender, _from, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible approve. /// `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf. /// @param _spender The address of the account able to transfer the tokens /// @param _amount The number of tokens to be approved for transfer /// @return `true`, if the approve can't be done, it should fail. function approve(address _spender, uint256 _amount) public erc20 returns (bool success) { require(balancesDB.setApprove(msg.sender, _spender, _amount)); emit Approval(msg.sender, _spender, _amount); return true; } /// @notice ERC20 backwards compatible allowance. /// This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public erc20 view returns (uint256 remaining) { return balancesDB.getAllowance(_owner, _spender); } function doSend( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { super.doSend(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking); if (mErc20compatible) { emit Transfer(_from, _to, _amount); } } function doBurn( address _operator, address _tokenHolder, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { super.doBurn(_operator, _tokenHolder, _amount, _data, _operatorData); if (mErc20compatible) { emit Transfer(_tokenHolder, address(0), _amount); } } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pragma solidity 0.5.8; import { ERC777 } from "./ERC777.sol"; import { CStore } from "./CStore.sol"; contract ERC777RemoteBridge is ERC777 { CStore public balancesDB; constructor( string memory _name, string memory _symbol, uint256 _granularity, uint256 _totalSupply, address _initialOwner, address[] memory _defaultOperators ) public ERC777(_name, _symbol, _granularity, new address[](0)) { balancesDB = new CStore(_totalSupply, _initialOwner, _defaultOperators); } /** * @return the total supply of the token */ function totalSupply() public view returns (uint256) { return balancesDB.getTotalSupply(); } /** * @notice Return the account balance of some account * @param _tokenHolder Address for which the balance is returned * @return the balance of `_tokenAddress`. */ function balanceOf(address _tokenHolder) public view returns (uint256) { return balancesDB.getBalance(_tokenHolder); } /** * @notice Return the list of default operators * @return the list of all the default operators */ function defaultOperators() public view returns (address[] memory) { return balancesDB.getDefaultOperators(); } /** * @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens at remote database. * @param _operator The operator that wants to be Authorized */ function authorizeOperator(address _operator) external { require(_operator != msg.sender, "Cannot authorize yourself as an operator"); if (balancesDB.getDefaultOperator(_operator)) { require(balancesDB.setRevokedDefaultOperator(_operator, msg.sender, false)); } else { require(balancesDB.setAuthorizedOperator(_operator, msg.sender, true)); } emit AuthorizedOperator(_operator, msg.sender); } /** * @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens at remote database. * @param _operator The operator that wants to be Revoked */ function revokeOperator(address _operator) external { require(_operator != msg.sender, "Cannot revoke yourself as an operator"); if (balancesDB.getDefaultOperator(_operator)) { require(balancesDB.setRevokedDefaultOperator(_operator, msg.sender, true)); } else { require(balancesDB.setAuthorizedOperator(_operator, msg.sender, false)); } emit RevokedOperator(_operator, msg.sender); } /** * @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` * address at remote database. * @param _operator address to check if it has the right to manage the tokens * @param _tokenHolder address which holds the tokens to be managed * @return `true` if `_operator` is authorized for `_tokenHolder` */ function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) { return _operator == _tokenHolder || balancesDB.getAuthorizedOperator(_operator, _tokenHolder); return (_operator == _tokenHolder // solium-disable-line operator-whitespace || balancesDB.getAuthorizedOperator(_operator, _tokenHolder) || (balancesDB.getDefaultOperator(_operator) && !balancesDB.getRevokedDefaultOperator(_operator, _tokenHolder))); } /** * @notice Helper function actually performing the sending of tokens using a backend database. * @param _from The address holding the tokens being sent * @param _to The address of the recipient * @param _amount The number of tokens to be sent * @param _data Data generated by the user to be passed to the recipient * @param _operatorData Data generated by the operator to be passed to the recipient * @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not * implementing `erc777_tokenHolder`. * ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer * functions SHOULD set this parameter to `false`. */ function doSend( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _data, _operatorData); require(_to != address(0), "Cannot send to 0x0"); // forbid sending to 0x0 (=burning) // require(mBalances[_from] >= _amount); // ensure enough funds // (Not Required due to SafeMath throw if underflow in database and false check) require(balancesDB.move(_from, _to, _amount)); callRecipient(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking); emit Sent(_operator, _from, _to, _amount, _data, _operatorData); //if (mErc20compatible) { emit Transfer(_from, _to, _amount); } } /** * @notice Helper function actually performing the burning of tokens. * @param _operator The address performing the burn * @param _tokenHolder The address holding the tokens being burn * @param _amount The number of tokens to be burnt * @param _data Data generated by the token holder * @param _operatorData Data generated by the operator */ function doBurn( address _operator, address _tokenHolder, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { revert("Burning functionality is disabled."); } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity 0.5.8; interface IERC644 { function getBalance(address _acct) external view returns(uint); function incBalance(address _acct, uint _val) external returns(bool); function decBalance(address _acct, uint _val) external returns(bool); function getAllowance(address _owner, address _spender) external view returns(uint); function setApprove(address _sender, address _spender, uint256 _value) external returns(bool); function decApprove(address _from, address _spender, uint _value) external returns(bool); function getModule(address _acct) external view returns (bool); function setModule(address _acct, bool _set) external returns(bool); function getTotalSupply() external view returns(uint); function incTotalSupply(uint _val) external returns(bool); function decTotalSupply(uint _val) external returns(bool); function transferRoot(address _new) external returns(bool); event BalanceAdj(address indexed Module, address indexed Account, uint Amount, string Polarity); event ModuleSet(address indexed Module, bool indexed Set); } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed pragma solidity 0.5.8; interface IERC777 { function name() external view returns (string memory); function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function granularity() external view returns (uint256); function defaultOperators() external view returns (address[] memory); function isOperatorFor(address operator, address tokenHolder) external view returns (bool); function authorizeOperator(address operator) external; function revokeOperator(address operator) external; function send(address to, uint256 amount, bytes calldata data) external; function operatorSend( address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; function burn(uint256 amount, bytes calldata data) external; function operatorBurn(address from, uint256 amount, bytes calldata data, bytes calldata operatorData) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed pragma solidity 0.5.8; interface IERC777TokensRecipient { function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed pragma solidity 0.5.8; interface IERC777TokensSender { function tokensToSend( address operator, address from, address to, uint amount, bytes calldata data, bytes calldata operatorData ) external; } pragma solidity ^0.5.0; import "./Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity 0.5.8; import "./Ownable.sol"; /** * @title Safe Guard Contract * @author Panos */ contract SafeGuard is Ownable { event Transaction(address indexed destination, uint value, bytes data); /** * @dev Allows owner to execute a transaction. */ function executeTransaction(address destination, uint value, bytes memory data) public onlyOwner { require(externalCall(destination, value, data.length, data)); emit Transaction(destination, value, data); } /** * @dev call has been separated into its own function in order to take advantage * of the Solidity's code generator to produce a loop that copies tx.data into memory. */ function externalCall(address destination, uint value, uint dataLength, bytes memory data) private returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly let x := mload(0x40) // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens at remote database. _operator The operator that wants to be Revoked/
function revokeOperator(address _operator) external { require(_operator != msg.sender, "Cannot revoke yourself as an operator"); if (balancesDB.getDefaultOperator(_operator)) { require(balancesDB.setRevokedDefaultOperator(_operator, msg.sender, true)); require(balancesDB.setAuthorizedOperator(_operator, msg.sender, false)); } emit RevokedOperator(_operator, msg.sender); }
13,062,953